I have been using this /\(\s*([^)]+?)\s*\)/ regex to remove outer brackets with PHP preg_replace function (Read more in my previous question Regex to match any character except trailing spaces).
This works fine when there is only one pair of brackets, but problem is when there is more, for example ( test1 t3() test2) becomes test1 t3( test2) instead test1 t3() test2.
I am aware of regex limitations, but it would be nice if I could just make it not matching anything if there is more then one pair of brackets.
So, example behavior is good enough:
( test1 test2 ) => test1 test2
( test1 t3() test2 ) => (test1 t3() test2)
EDIT:
I would like to keep trimming trailing white spaces inside removed brackets.
You can use this recursive regex based code that will work with nested brackets also. Only condition is that brackets should be balanced.
OUTPUT: