Search code examples
phptokenizeexplode

explode string only by outer delimter in PHP


I have a source from where I get pairs of latitudes and longitudes where they are separated by comma and enclosed in parenthesis, and pairs themselves are also separated by commas.I want to fetch each pair and store in a table

enter image description here

Tried:

$str = "(a,b),(c,d),(e,f),(g,h)"; //a,c,e,g = latitudes b,d,f,h = longitudes

$str = explode(',' , $str);

print_r($str);

Desired:

Array
(
    [0] => (a,b)
    [1] => (c,d)
    [2] => (e,f)
    [3] => (g,h)
)

Actual:

Array
(
    [0] => (a
    [1] => b)
    [2] => (c
    [3] => d)
    [4] => (e
    [5] => f)
    [6] => (g
    [7] => h)
)

My idea was once I get my desired output I can loop over them and ..

$tmp = trim('(a,b)', '()'); //  "a,b"
$res = explode(',', $tmp);  //  ['a','b'] 
/* store $res[0] and $res[1] */

So how can I get the desired result or is there any better way?


Solution

  • Maybe

    $str = "(a,b),(c,d),(e,f),(g,h)"; //a,c,e,g = latitudes b,d,f,h = longitudes
    $str = str_replace('),', ')|', $str);
    $str = explode('|',  $str);
    print_r($str);
    
    Output:
    Array
    (
        [0] => (a,b)
        [1] => (c,d)
        [2] => (e,f)
        [3] => (g,h)
    )