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

PHP regex expression extract latitude & longitude from JS function

我正在使用 simple_html_dom PHP library 抓取页面的一些内容。我想从页面中提取纬度和经度,但我需要一个正则表达式来访问这些值,因为这些值仅在页面上的 Javascript 函数中可用:

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

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

你可以试试

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

使用这个正则表达式:

/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

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

<?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

优化和正则表达式并没有真正与这个简单的解析齐头并进。
这是使用 Substr 和 strpos 的 "optimized" 解决方案。

$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