从 Google 地图解析 KML 坐标 - PHP

Parsing KML coordinates from Google Maps - PHP

我尝试使用 PHP 从 Google KML 文件中收集坐标(经度和纬度)。

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

我可以用逗号分解坐标,得到如下结果:

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

为了得到这个结果,我正在使用:

explode(',', $coordinates);

如何用逗号分解坐标?

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

我需要的结果:

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

如何删除逗号后的数字?

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

谢谢,

您可以用逗号分隔字符串,后跟数字和点:

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

参见regex demo

详情

  • , - 一个逗号...
  • (?=\d+\.) - 紧跟 1 个或多个数字 (\d+) 和一个点 (\.)。

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 )

非正则表达式解决方案是使用 strpos 找到第二个逗号的位置并在那里拆分字符串。

$str = "45.51088930166307,51,52.52216552154544,75";
if(substr_count($str, ",")>1){
    $pos = strpos($str, ",", strpos($str, ",")+1); // find second comma
    // The inner strpos finds the first comma and uses that as the starting point to find the second comma.
    $arr = [substr($str, 0,$pos), substr($str,$pos+1)]; //split string at second comma
}else{
    $arr = explode(",", $str);
}
var_dump($arr);

https://3v4l.org/nnrlV