使用preg_match_all 查找所有 JSON 并将其存储到一个数组中,如下所示:
$text = '[22-Aug-2017 16:19:58 America/New_York] WP_Community_Events::maybe_log_events_response: Valid response received. Details: {"api_url":"https:\/\/api.wordpress.org\/events\/1.0\/","request_args":{"body":{"number":5,"ip":"192.168.99.0","locale":"en_GB","timezone":"America\/New_York"}},"response_code":200,"response_body":{"location":{"ip":"47.197.97.47"},"events":"5 events trimmed."}}';
preg_match_all('/\{(?:[^{}]|(?R))*\}/x', $text, $matches);
echo '<pre>';
print_r($matches[0]);
这会产生:
Array
(
[0] => {"api_url":"https:\/\/api.wordpress.org\/events\/1.0\/","request_args":{"body":{"number":5,"ip":"192.168.99.0","locale":"en_GB","timezone":"America\/New_York"}},"response_code":200,"response_body":{"location":{"ip":"47.197.97.47"},"events":"5 events trimmed."}}
)
您可以阅读更多内容:
Extracting the JSON string from given text
或者,如果您想要相反并删除 JSON 并保留字符串,那么您可以使用 preg_replace 来执行此操作:
$text = '[22-Aug-2017 16:19:58 America/New_York] WP_Community_Events::maybe_log_events_response: Valid response received. Details: {"api_url":"https:\/\/api.wordpress.org\/events\/1.0\/","request_args":{"body":{"number":5,"ip":"192.168.99.0","locale":"en_GB","timezone":"America\/New_York"}},"response_code":200,"response_body":{"location":{"ip":"47.197.97.47"},"events":"5 events trimmed."}}';
$cleantext = preg_replace('~\{(?:[^{}]|(?R))*\}~', '', $text);
echo $cleantext;
来自PHP: How to extract JSON strings out of a string dump的信用
这会产生:
[22-Aug-2017 16:19:58 America/New_York] WP_Community_Events::maybe_log_events_response: Valid response received. Details: