首页 > 解决方案 > 用PHP提取两个字符串之间的数据

问题描述

我有以下字符串:

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

我想提取latlng数据。

这是我的尝试:

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

但它不起作用。

你能帮帮我吗?

谢谢。

标签: phpregex

解决方案


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

推荐阅读