regex - Extract data between two string with PHP

57

I've the following string:

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

I would like to extract thelat andlng 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.

232

Answer

Solution:

json_decode is much more reliable than regex. Add braces and a value for the missing"address" element and you can index directly into the result:

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

Answer

Solution:

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

975

Answer

Solution:

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

Values in group 1 and group 2

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 )

People are also looking for solutions to the problem: php - org.json.JSONException: Value DB of type java.lang.String cannot be converted to JSONObject

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.