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.