2

I'm trying to break down a mathematic expression into pieces and I was trying to use the Regex /\([^)]+\)/ to do the trick (found here). But reading that answer, I understood that this Regex will be searching for the first closing parenthesis ) to finish, giving me trouble when handling, for instance:

(2*x^2 + 5*x - (2*x - 3)^(1/2))/(1 + x)
^                      ^      ^
START                IGNORE FINISH

Since I'm not really good with coming up with Regex, I'm wondering if I should handle this with strpos, substr and str_replace or is there a different Regex to apply to preg_match_all and get the correct set of parenthesis?

Note: This function will be recursive in order to solve inner parenthesis.

EDIT:

My expected output in this case:

$array = null;
$expression = '(2*x^2 + 5*x - (2*x - 3)^(1/2))/(1 + x)';
$expression = str_replace(' ', '', $expression);
preg_match_all('MAGIC EXPRESSION HERE', , $array);
print_r($array);

// Output
array(
    [0] => (2*x^2+5*x-(2*x-3)^(1/2))
    [1] => (1+x)
)

Thanks.

Community
  • 1
  • 1
Marco Aurélio Deleu
  • 4,103
  • 4
  • 32
  • 58

1 Answers1

6

To match the nested parenthesis a recursive attempt could be:

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

At (?R) the pattern is pasted from start. Same like (?0)

See example at regex101; Regex FAQ

Community
  • 1
  • 1
Jonny 5
  • 11,051
  • 2
  • 20
  • 42
  • It works perfectly, sadly I find it so hard to understand. – Marco Aurélio Deleu Oct 03 '14 at 15:55
  • @MarcoAurélioDeleu Might want to see the link, that I provided from [rexegg](http://www.rexegg.com/regex-recursion.html) or [regular-expressions.info](http://www.regular-expressions.info/recurse.html) has also a nice tutorial :) – Jonny 5 Oct 03 '14 at 16:01