简体   繁体   English

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

[英]Extract data between two string with PHP

I've the following string: 我有以下字符串:

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

I would like to extract the lat and lng datas. 我想提取的latlng DATAS。

This is my try: 这是我的尝试:

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

But it doesn't work. 但这是行不通的。

Could you please help me please ? 你能帮我吗?

Thanks. 谢谢。

json_decode is much more reliable than regex. json_decode比正则表达式更可靠。 Add braces and a value for the missing "address" element and you can index directly into the result: 为缺少的"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"];

Output: 输出:

lat: 45.491834  lng:  -73.606953

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

Values in group 1 and group 2 组1和组2中的值

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

Php Code 邮递区号

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";
     }
 }

 >

Output 输出量

( lat, long ) = ( 45.491834, -73.606953 )
( lat, long ) = ( 44.491834, -72.606953 )
( lat, long ) = ( 43.491834, -71.606953 )

This expression would likely extract our desired latitude and longitude data in this capturing group (.+?) , as it also removes the undesired spaces: 此表达式可能会在此捕获组(.+?)提取所需的纬度和经度数据,因为它还会删除不需要的空格:

("lat":|"lng":)"\s*(.+?)\s*"

Test 测试

$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";
}

Output 输出量

45.491834
-73.606953

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM