2017-09-04 28 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

相關問題