在PHP中使用preg_match_all和json_decode可以从字符串中提取JSON数据。
preg_match_all函数可以用来从一个字符串中匹配多个正则表达式的结果。json_decode函数可以将JSON格式的字符串转换成PHP数组或对象。
下面是一个示例代码,它可以从字符串中提取所有JSON数据并将其转换为PHP数组:
$string = 'Some text before {"name": "John", "age": 30} and more text after. Another JSON object: {"name": "Alice", "age": 25}';
preg_match_all('/\{.*?\}/', $string, $matches);
$jsons = $matches[0];
$data = array();
foreach ($jsons as $json) {
$data[] = json_decode($json, true);
在这个例子中,
注意,json_decode函数的第二个参数设置为true,以便将JSON对象转换为关联数组而不是对象。
希望这可以帮助你理解如何使用preg_match_all和json_decode函数从字符串中提取JSON数据。如果你有任何进一步的问题,请告诉我。