Search code examples
phparrayssplitexplodedelimited

Split a string with two delimiters into two arrays (explode twice)


How can I split this string of comma-separated dimensions into two arrays? The string may have many items in it, but it will always have the same two alternating delimiters (exes and commas).

$str = "20x9999,24x65,40x5";

I need to get two arrays from this string:

$array1 = [20, 24, 40];
$array2 = [9999, 65, 5];

I've tried many implementations of preg_split(), array_slice(), and regex. I can't get it done.


Solution

  • You can explode the string by commas, and then explode each of those values by x, inserting the result values from that into the two arrays:

    $str = "20x9999,24x65,40x5";
    
    $array1 = array();
    $array2 = array();
    foreach (explode(',', $str) as $key => $xy) {
        list($array1[$key], $array2[$key]) = explode('x', $xy);
    }
    

    Alternatively, you can use preg_match_all, matching against the digits either side of the x:

    preg_match_all('/(\d+)x(\d+)/', $str, $matches);
    $array1 = $matches[1];
    $array2 = $matches[2];
    

    In both cases the output is:

    Array
    (
        [0] => 20
        [1] => 24
        [2] => 40
    )
    Array
    (
        [0] => 9999
        [1] => 65
        [2] => 5
    )
    

    Note that as of PHP7.1, you can use array destructuring instead of list, so you can just write

    [$array1[$key], $array2[$key]] = explode('x', $xy);
    

    instead of

    list($array1[$key], $array2[$key]) = explode('x', $xy);
    

    You can use this to simplify the assignment of the result from preg_match_all as well:

    [, $array1, $array2] = $matches;
    

    Demo on 3v4l.org