PHP 正则表达式从 JS 函数中提取纬度和经度



我正在使用simple_html_dom php库来刮擦页面的某些内容。我想从页面上提取纬度和经度,但是我需要一个正则表达式来访问这些值,因为这些值仅在JavaScript函数的页面上可用:

function loadMap() { setTimeout("setMap(39.364016, 3.226783, 'Hotel Casa', 
'icon.png', 'key')", 200)};

我在字符串中得到了上述示例。从此字符串中提取纬度(39.364016)和经度(3.226783)的优化正则表达式表达式(使用PHP)是什么?我是Regex表达的新手,因此到目前为止我的尝试还没有成功,我希望有人可以帮助我。谢谢。

使用命名捕获,您可能会发现它更清晰:

<?php
$html = <<<HTML
<html>
...
    function loadMap() { setTimeout("setMap(39.364016, 3.226783, 'Hotel Casa',
'icon.png', 'key')", 200)};
...
</html>
HTML;
$regex = '/setMap((?P<latitude>[0-9.-]+), (?P<longitude>[0-9.-]+)/';
$matches = [];
preg_match($regex, $html, $matches);
echo "Latitude: ", $matches['latitude'], ", Longitude: ", $matches['longitude'];
// Latitude: 39.364016, Longitude: 3.226783

使用此正则表达式:

/setMap((-?d+.?d*), ?(-?d+.?d*)/

详细信息

setMap(   match that string, literally, with the open parentheses
-?        optional minus symbol
d+        a digit, one or more times
.?        a literal dot, optional (in the rare case you get an integer)
d         a digit, 0 or more times (in the rare case you get an integer)
, ?         an comma followed optionally by a space

demo

您可以尝试

 /[0-9]{1,3}[.][0-9]{4,}/ 

优化和正则表达式并没有真正与这种简单的解析息息相关。
这是使用substr和strpos的"优化"解决方案。

$str =  <<<EOD
function loadMap() { setTimeout("setMap(39.364016, 3.226783, 'Hotel Casa', 
'icon.png', 'key')", 200)}
EOD;
$pos = strpos($str, "setMap(") + 7; //find position of setMap(
$latlon = Substr($str, $pos, strpos($str, ", '")-$pos); // substring from setMap to `, '`
List($lat, $lon) = explode(", ", $latlon); // explode the latlon to each variable.
Echo $lat . " " . $lon;

https://3v4l.org/qdil4

最新更新