Let's say I have this string:
1 + 2 * (3 + (23 + 53 - (132 / 5) + 5) - 1) + 2 / 'test + string' - 52
I want to split it into an array of operators and non-operators, but anything between the ()
and '
must not be split.
I want the output to be:
[1, "+", 2, "*", "(3 + (23 + 53 - (132 / 5) + 5) - 1)", "+", 2, "/", "'test + string'", "-", 52]
I'm using this code:
preg_split("~['\(][^'()]*['\)](*SKIP)(*F)|([+\-*/^])+~", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
The technique does what I want with the operators and the '
, but not for ()
. However it only keeps (132 / 5)
(the deepest nested parenthetical expression) and splits all the other ones, giving me this output:
[1, "+", 2, "*", "(3", "+", "(23", "+", 53, "-", "(132 / 5)", "+", "5)", "-", "1)", "+", 2, "/", "'test + string'", "-", 52]
How can I ensure that the outermost parenthetical expression and all of its contents remain together?