June 14th, 2013, 03:28 PM
Explode with regex
I'm hopeless/intellectually lazy with regex.
I need to turn a string like this . . .
'one, two, three, (four, five), six'
. . . into an array like this . . .
 => 'one'
 => 'two'
 => 'three'
 => '(four, five)'
 => 'six'
. . . so basically explode the string by ',' delimiter except where the ',' delimiter is inside brackets.
Appreciate any help.
Last edited by mattzo; June 14th, 2013 at 05:01 PM.
June 14th, 2013, 04:15 PM
$list = 'one, two, three, (four, five), six';
preg_match_all('/(?<=^ |, )(?:\([^)]*\)|[^,]*)/', $list, $elements);
June 14th, 2013, 04:56 PM
Thanks so much! That's nearly perfect - except the array contains only four values - the first one ('one') is missing.
I suppose I could add a dummy value to the front of the string - but is there a 'cleaner' way to do it?
June 14th, 2013, 05:09 PM
Remove the stray space after the caret.
Comments on this post
June 15th, 2013, 06:57 AM