Search code examples
phparraysregexpreg-match

PHP: preg_match_all() - divide an array


I have the following code:

$str = '{"ok1", "ok2"}, 
        {"ok3", "ok4"}, 
        {"ok5", "ok6"}';

preg_match_all('/"([^"]*)"/', $str, $matches);

print_r($matches[1]);

which outputs this: Array ( [0] => ok1 [1] => ok2 [2] => ok3 [3] => ok4 [4] => ok5 [5] => ok6 )

It works perfect but I want to make it array1, array2 and array3. So it will divide the array depending on the tags inside {}

i.e.

 `array1` will be  `array("ok1", "ok2")`;
 `array2` will be  `array("ok3", "ok4")`; 
 `array3` will be  `array("ok5", "ok6")`; 

Solution

  • Kind of an overkill, but you could indeed achieve it with two regular expressions as well (if this is not some JSON code):

    <?php 
    $string = '{"ok1", "ok2"}, {"ok3", "ok4"}, {"ok5", "ok6"}';
    $regex = '~(?<=}),\s~';
    $result = array();
    $parts = preg_split($regex, $string);
    foreach ($parts as $part) {
        preg_match_all('~"(?<values>[^"]+)"~', $part, $elements);
        $result[] = $elements["values"];
    }
    echo $result[0][1]; // ok2
    ?>