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,132
  • 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

4 Answers4

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
  • 311,322
  • 76
  • 447
  • 566
  • 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
  • 33,269
  • 52
  • 129
  • 197
0

If you only want the content between brackets I think you should use preg_match and not preg_split

  1. Extract whatever is in brackets using regular expressions
  2. php preg_split() to find text inbetween two words
Community
  • 1
  • 1
Brock Hensley
  • 3,569
  • 2
  • 26
  • 45
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,474
  • 1
  • 18
  • 14