用PHP提取两个字符串之间的数据

时间:2019-06-15 15:41:46

标签: php regex

我有以下字符串:

$html = '"id":75549,"name":"Name","lat":"45.491834","lng":" -73.606953","address"';

我想提取latlng数据。

这是我的尝试:

$lat = preg_match_all('#lat":"(.*?)","lng#', $html, $matches);
$lat = matches[1];

但这不起作用。

能请你帮我吗?

谢谢。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

"lat":"\s*([^"]*?\s*"),"lng":"\s*([^"]*?\s*)"\K

第1组和第2组中的值

https://regex101.com/r/jDWL84/1

Php代码

Sandbox Demo

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

答案 2 :(得分:2)

此表达式可能会在此捕获组(.+?)中提取我们所需的纬度和经度数据,因为它还会删除不需要的空格:

("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

Demo