Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces before and after parentheses

I'm trying to remove one or more spaces after open parentheses and before close parentheses for both round and square parentheses.

$s = "This is ( a sample ) [ string ] to play with"

expected result:

"This is (a sample) [string] to play with"

I managed to remove the space before:

$s = preg_replace('/\s+(?=[\])])/', '', $s);

result:

"This is ( a sample) [ string] to play with"

but not the spaces after the parentheses!

like image 446
Nicero Avatar asked Dec 19 '22 00:12

Nicero


1 Answers

Try this regex:

(?<=[([]) +| +(?=[)\]])

Click for Demo

Replace the matches with a blank string

Explanation:

  • (?<=[([]) + - matches 1+ occurrences of a space which are preceded by either a [ or (
  • | - OR
  • +(?=[)\]]) - matches 1+ occurrences of a space which are followed either by ) or ]
like image 88
Gurmanjot Singh Avatar answered Dec 28 '22 07:12

Gurmanjot Singh