从字符串中提取long / lat

时间:2010-08-15 12:44:11

标签: php regex

HI,

我有一个可以包含经度和纬度的字符串。该字符串可以包含任何内容,但如果它确实包含lon / lat,那么我想使用php提取它。我想我需要一个正则表达式,但我不知道如何解决这个问题。该字符串可以包含任何内容:

随机字符串dfdff33338983 33.707352,-116.272797 more dfdfndfdf

2 个答案:

答案 0 :(得分:4)

如果字符串可以包含任何,那么 no 正则表达式,或者确实可以提取经度和纬度的任何代码片段。

可以使用以下字符串确认:

7.123456,40.404040 is nothing like 33.707352,-116.272797 or 99.111222,-22.333444.

其中哪一个是纬度?

您可以尝试以下方式:

\b-?\d+\.\d{6},-?\d+\.\d{6}\b

作为起点。

答案 1 :(得分:2)

您可以使用此匹配:

.*\s(.*),(.*?)\s.*

请参阅rubular中的此答案。

在php中回答:

$txt = "dfdff333 38983 33.707352,-116.272797 dfd fndfdf";
$lat = preg_replace("/.*\s(.*),.*?\s.*/", "$1", $txt);
$lon = preg_replace("/.*\s.*,(.*?)\s.*/", "$1", $txt);

echo $lat."\n"; // 33.707352
echo $lon."\n"; // -116.272797

注意:我使用逗号作为分隔符。


编辑:您可以使用更具体的正则表达式,例如

$lat = preg_replace("/.*\s(-?\d+\.\d+),-?\d+\.\d+?\s.*/", "$1", $txt);
$lon = preg_replace("/.*\s-?\d+\.\d+,(-?\d+\.\d+?)\s.*/", "$1", $txt);

Tks @soapbox。

相关问题