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!
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With