I have a string like
"first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"
I want to explode it to array
Array (
0 => "first",
1 => "second[,b]",
2 => "third[a,b[1,2,3]]",
3 => "fourth[a[1,2]]",
4 => "sixth"
}
I tried to remove brackets:
preg_replace("/[ ( (?>[^[]]+) | (?R) )* ]/xis",
"",
"first,second[,b],third[a,b[1,2,3]],fourth[a[1,2]],sixth"
);
But got stuck one the next step
PHP’s regex flavor supports recursive patterns, so something like this would work:
which will print:
Array ( [0] => first [1] => second[,b] [2] => third[a,b[1,2,3]] [3] => fourth[a[1,2]] [4] => sixth )The key here is not to
split, butmatch.Whether you want to add such a cryptic regex to your code base, is up to you 🙂
EDIT
I just realized that my suggestion above will not match entries starting with
[. To do that, do it like this:which prints:
Array ( [0] => first [1] => second[,b] [2] => third[a,b[1,2,3]] [3] => fourth[a[1,2]] [4] => sixth [5] => [s,[,e,[,v,],e,],n] )