Search code examples
phpregexkmlgoogle-earthkmz

Parsing KML coordinates from Google Maps - PHP


I try to collect the coordinates (longitude and latitude) from the Google KML file with PHP.

<Point>
    <coordinates>45.51088930166307,52.52216552154544</coordinates>
</Point>

I can explode the coordinates with comma and get results as below:

[0] => 45.51088930166307
[1] => 52.52216552154544

To get this results I'm using:

explode(',', $coordinates);

How do I explode the coordinates with commas?

<Point>
    <coordinates>45.51088930166307,51,52.52216552154544,75</coordinates>
</Point>

Results that I need:

[0] => 45.51088930166307,51
[1] => 52.52216552154544,75

And how do I remove the digits after commas?

[0] => 45.51088930166307
[1] => 52.52216552154544

Thanks,


Solution

  • You may split the string with a comma that is followed with digits and a dot:

    preg_split('~,(?=\d+\.)~', $s)
    

    See the regex demo.

    Details

    • , - a comma that is ...
    • (?=\d+\.) - immediately followed with 1 or more digits (\d+) and a dot (\.).

    PHP demo:

    $s = '45.51088930166307,51,52.52216552154544,75';
    $res = preg_split('~,(?=\d+\.)~', $s);
    print_r($res);
    // => Array ( [0] => 45.51088930166307,51 [1] => 52.52216552154544,75 )