Search code examples
phpregexparenthesesnon-greedy

RegExp in PHP. Get text between first level parentheses


I have two type of strings in one text:

a(bc)de(fg)h

a(bcd(ef)g)h

I need to get text between first level parentheses. In my example this is:

bc

fg

bcd(ef)g

I tried to use next regular expression /\((.+)\)/ with Ungreedy (U) flag:

bc

fg

bcd(ef

And without it:

bc)de(fg

bcd(ef)g

Both variants don't do what I need. Maybe someone know how solve my issue?


Solution

  • This question pretty much has the answer, but the implementations are a little ambiguous. You can use the logic in the accepted answer without the ~s to get this regex:

    \(((?:\[^\(\)\]++|(?R))*)\)
    

    Tested with this output:

    enter image description here