2017-09-04 29 views
1

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

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

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

+0

'/setMap\((\d+\.\d*),(\ d + \ \ d *)/' – raina77ow

回答

1

USI NG命名捕获,你可能会发现一个更清楚一点:

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

不错,但不要逃避'.'或' - 那里。 – pguardiario

0

您可以尝试

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

使用这个表达式:

/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

优化和正则表达式并没有真正齐头并进这个简单的解析。
这是一个使用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

相关问题