0

With the following string:

$str = '["one","two"],a,["three","four"],a,,a,["five","six"]';

preg_split( delimiter pattern, $str );

How would I have to set up the delimiter pattern to obtain this result:

$arr[0] = '["one","two"]';
$arr[1] = '["three","four"]';
$arr[2] = '["five","six"]';

In other words, is there a way to split at the pattern ',a,' AND ',a,,a,' BUT check for ',a,,a,' first because ',a,' is a sub string of ',a,,a,'?

Thanks in advance!

Philipp Werminghausen
  • 1,142
  • 11
  • 29
  • 3
    Are you ok with using preg_match instead? – Pitchinnate Mar 07 '13 at 22:00
  • possible duplicate of [How to split string by ',' unless ',' is within brackets using Regex?](http://stackoverflow.com/questions/732029/how-to-split-string-by-unless-is-within-brackets-using-regex) or [PHP: split string on comma, but NOT when between braces or quotes?](http://stackoverflow.com/q/15233953) – mario Mar 07 '13 at 22:03
  • Yes I would be fine with using preq_match too. – Philipp Werminghausen Mar 07 '13 at 22:09

3 Answers3

1

It looks like what you're actually trying to do is separate out the square bracketed parts. You could do that like so:

$arr = preg_split("/(?<=\])[^[]*(?=\[)/",$str);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I tested your pattern, should be changed to: `/(?<=\])[^[]*(?=\[)/` –  Mar 07 '13 at 22:09
1

If it can only be ,a, and ,a,,a,, then this should be enough:

preg_split("/(,a,)+/", $str);
Emanuil Rusev
  • 34,563
  • 55
  • 137
  • 201
0

Take a look at this code:

$result = array();

preg_match_all("/(\[[^\]]*\])/", '["one","two"],a,["three","four"],a,,a,["five","six"]', $result);

echo '<pre>' . print_r($result, true);

It will return:

Array
(
    [0] => Array
        (
            [0] => ["one","two"]
            [1] => ["three","four"]
            [2] => ["five","six"]
        )

    [1] => Array
        (
            [0] => ["one","two"]
            [1] => ["three","four"]
            [2] => ["five","six"]
        )
)
MatRt
  • 3,494
  • 1
  • 19
  • 14