Reputation: 19915
As long as there are no nested parenthesis, it is easy to match the text between parentheses using regular expressions. I use
preg_match('#\(([^)]*)\)#', $subject, $matches);
and I get the whole expression with $matches[0]
and the part between the parentheses with $matches[1]
.
But if I have $subject = 'test (with (nested) parenthesis)';
it will return (of course) 'with (nested'
instead of 'with (nested) parenthesis'
. How do I need to modify the regular expression to get the expected result ?
Upvotes: 1
Views: 59
Reputation: 71538
You can make use of a recursive regex:
\(((?:[^()]+|\((?1)\))+)\)
(?1)
matches the first capture group.
Upvotes: 2