Looking at this I can see this will group the (?: ) will group the bracket segment of the subject together (had to read d11's regex crash course ), however I'm trying to capture the value of all the text inside each bracket aswell.
I took I shot at adapting feyd's regex with only limited success.
It can only remember the last bracketed reference unless you add more of the subpattern. To accurately capture all of them without knowing how many there are requires two patterns. One to capture the entire variable reference, the second to capture the contents.
If it's only working with the fully captured variable, using preg_split() could work better.
I've tried the patterns above, however I am not completely getting my desired results. If I have an element with no name, simply foo[bar][] it is being ignored by the regex and only returning foo, bar.. any idea how to modify '/[^\[\]]+/' for blank values?
to allow for empty keys. However, I am still interested in pursuing the preg_split() option. So far I havn't been succesful with it, since passing a string to
foobar[f1][f2][] would be rendered to the following by preg_split()
Selects every substring that is separated by square brackets or whitespace. It works fine except for when empty square brackets pop up. In that case I agree preg_split() will be a better solution.
Jcart wrote:there should only be 4 array elements I guess this is because it is splitting the last bracket at the end of the string.. Any ideas?
You'll always end up with one final empty element because the last char of your string is ']'. I tried to cook something up with a lookahead construction to prevent this. No success however. I suggest to just use a function like array_pop() to always chop the last element off the array.
Also feyd's split pattern can be optimized a bit.
Before:
GeertDD wrote:No success however. I suggest to just use a function like array_pop() to always chop the last element off the array.
Yea I figured so, and was exactly what I wanted to avoid.. since not all strings supplied will have brackets at all therefore will not have the empty element..
I think I'll stick to the preg_match_all then...