Lorenz Meyer
Lorenz Meyer

Reputation: 19915

Match expression between paretheses with nested paretheses

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

Answers (2)

Jerry
Jerry

Reputation: 71538

You can make use of a recursive regex:

\(((?:[^()]+|\((?1)\))+)\)

regex101 demo

(?1) matches the first capture group.

Upvotes: 2

Toto
Toto

Reputation: 91430

Replace [^)]* by .*:

preg_match('#\((.*)\)#', $subject, $matches);

Upvotes: 0

Related Questions