Search code examples
phpregexpreg-match

Get text inside parentheses include text with more parentheses?


I have a variable:

$str = "i do not need this datavar(i need this (also this) and this) i do not need this";

I have the following expression but returns only the content until the first pharenteses and I need everything until the last or second pharenteses.

$regex2 = '#(datavar\([^)]+\))#';

is there a way to have everything in the text and finish the match until the second parentheses (it can have more).


Solution

  • You can get the text until the second closing parenthesis or until the last (or any fixed number). But I don't know how to use pcre to check for balance. Here is the code for second and last:

    $str = "i do not need this datavar(i need this (also this) and this) i do not need this";
    $regex2 = '#datavar\(([^)]+\)[^)]+)#'; //second )
    $regex2 = '#datavar\((.+)\)#'; //last )
    preg_match_all($regex2,$str, $m);
    var_dump($m[1]);