[英]Extract data between two string with PHP
我有以下字符串:
$html = '"id":75549,"name":"Name","lat":"45.491834","lng":" -73.606953","address"';
我想提取的lat
和lng
DATAS。
这是我的尝试:
$lat = preg_match_all('#lat":"(.*?)","lng#', $html, $matches);
$lat = matches[1];
但这是行不通的。
你能帮我吗?
谢谢。
json_decode
比正则表达式更可靠。 为缺少的"address"
元素添加花括号和一个值,您可以直接在结果中建立索引:
<?php
$html = '"id":75549,"name":"Name","lat":"45.491834","lng":" -73.606953","address"';
$decoded = json_decode('{'.$html.':""}', true);
echo "lat: ".$decoded["lat"]." lng: ".$decoded["lng"];
输出:
lat: 45.491834 lng: -73.606953
"lat":"\\s*([^"]*?\\s*"),"lng":"\\s*([^"]*?\\s*)"\\K
组1和组2中的值
https://regex101.com/r/jDWL84/1
邮递区号
<?php
$str = '
"id":75549,"name":"Name","lat":"45.491834","lng":" -73.606953","address"
"id":75550,"name":"Name","lat":"44.491834","lng":" -72.606953","address"
"id":75551,"name":"Name","lat":"43.491834","lng":" -71.606953","address"
';
$cnt = preg_match_all('/"lat":"\s*([^"]*?\s*)","lng":"\s*([^"]*?\s*)"\K/', $str, $latlng, PREG_SET_ORDER );
if ( $cnt > 0 )
{
// print_r ( $latlng );
for ( $i = 0; $i < $cnt; $i++ )
{
echo "( lat, long ) = ( " . $latlng[$i][1] . ", " . $latlng[$i][2] . " )\n";
}
}
>
输出量
( lat, long ) = ( 45.491834, -73.606953 )
( lat, long ) = ( 44.491834, -72.606953 )
( lat, long ) = ( 43.491834, -71.606953 )
此表达式可能会在此捕获组(.+?)
提取所需的纬度和经度数据,因为它还会删除不需要的空格:
("lat":|"lng":)"\s*(.+?)\s*"
$re = '/("lat":|"lng":)"\s*(.+?)\s*"/m';
$str = '"id":75549,"name":"Name","lat":"45.491834","lng":" -73.606953","address"';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches[0][2]);
var_dump($matches[1][2]);
foreach ($matches as $key => $value) {
echo $value[2] . "\n";
}
45.491834
-73.606953
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.