【问题标题】:Parsing KML coordinates from Google Maps - PHP从谷歌地图解析 KML 坐标 - PHP
【发布时间】:2018-10-17 06:49:42
【问题描述】:

我尝试使用 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

谢谢,

【问题讨论】:

  • 获取长度/2,然后剪掉
  • 如果第一个逗号后面的数字长度不同,@VasylZhuryk 将不起作用。例如x.xx,99,x.xx,100
  • 为什么要投反对票?问题重复了吗?
  • 感谢 Vasyl Zhuryk 和 Andreas 的回复!

标签: php regex kml google-earth kmz


【解决方案1】:

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

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 )

【讨论】:

  • 感谢@Wiktor Stribiżew!这工作很棒。您知道如何删除逗号后的数字吗? // => 数组 ([0] => 45.51088930166307 [1] => 52.52216552154544)
  • @HossamEdani 使用preg_match_all('~\d+\.\d+~', $s, $matches),见PHP demo
  • 非常感谢@Wiktor Stribiżew!这个也很好用!我用你的方式使用 preg_split 然后用逗号分解它并忽略逗号后面的部分 $coordinates = '45.51088930166307,51,52.52216552154544,75'; $longitude = explode(",", preg_split('~,(?=\d+\.)~', $coordinates)[0])[0]; $latitude = explode(",", preg_split('~,(?=\d+\.)~', $coordinates)[1])[0]; ideone.com/03vJoE您的回答非常有用,非常有帮助,再次感谢!
【解决方案2】:

非正则表达式的解决方案是使用 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

【讨论】:

  • 感谢您的回答,如果其中一个坐标没有逗号,则此方法无效 条件 1:$str = "45.51088930166307,52.52216552154544,75";条件二:$str = "45.51088930166307,51,52.52216552154544";我认为我们需要先计算逗号,然后再拆分它。
  • 这种方式与 Wiktor Stribiżew 一样工作得非常好。我使用了 Wiktor Stribiżew 的方式,因为它的代码有点短,但这个也不错。非常感谢您的回答。非常感谢!
猜你喜欢
  • 2013-10-12
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 2012-09-08
  • 2012-08-06
  • 2011-04-13
  • 2015-02-05
  • 2012-10-18
相关资源
最近更新 更多