php谷歌地图正则表达式preg_match

时间:2017-04-30 13:51:13

标签: php preg-match-all

我有这个数据

  var companies = [{"name":"Beliaa","lat":"30.043438999999999","lng":"31.239159999999998","infowindow":{"title":"Beliaa","address":"28 El Falaky St., Bab El Louk, Downtown, Cairo"}}];
translator.add("Rated Successfully", "Rated Successfully");
translator.add("Reviewed Successfully", "Your review has been submitted and will be published as soon as possible. Thanks for sharing!");

我想要

纬度:30.043438999999999 和 LNG:31.239159999999998

使用preg_match

2 个答案:

答案 0 :(得分:1)

如果您尝试在PHP中解析JS代码

$subject = <<<'__EOS__'
 var companies = [{"name":"Beliaa","lat":"30.043438999999999","lng":"31.239159999999998","infowindow":{"title":"Beliaa","address":"28 El Falaky St., Bab El Louk, Downtown, Cairo"}}];
translator.add("Rated Successfully", "Rated Successfully");
translator.add("Reviewed Successfully", "Your review has been submitted and will be published as soon as possible. Thanks for sharing!");
__EOS__;


if(preg_match('/"lat":"(.*?)"/', $subject, $matches))
  echo "lat:{$matches[1]}";
else
  echo 'not found';

由于您的源代码字段是一个非常简单的代码段,因此您也可以保持正则表达式的简单性。搜索到的字符串由文字"lat":" ... "包围。括号定义了在(.*?)中捕获的子模式$matches[1]。点表示“任意字符”,星号是量词表示0次或更多次,问号使得量化表达式不合理,因此它停止在此表达式后面的下一个匹配模式(在这种情况下为引号)。否则,您将获得整个字符串,直到sharing!"(找到的最后一个引号)。

答案 1 :(得分:0)

Quasimodo的答案会有效,但可能会更好。 以下方法使用更快的正则表达式模式,并消除(浪费)使用捕获组的需要。

单线方法:

list($lat,$lng)=preg_match_all('/"l(?:at|ng)":"\K[\d\.]+/',$in,$out)?$out[0]:['',''];
echo "lat:$lat<br>";
echo "lng:$lng";

输出:

lat:30.043438999999999
lng:31.239159999999998

正则表达式模式中的\K会将您想要的值存储在&#34; fullstring&#34;子阵。该技术可将阵列膨胀降低50%。此部分:l(?:at|ng)将有效匹配latlng。而且:[\d\.]+将匹配您需要的整个十进制子字符串。

list()会将匹配的值分配给即用型变量;现在你可以根据需要使用这些变量。

相关问题