简体   繁体   English

使用 preg_match 以字符串形式获取 json 格式

[英]get json format in string with preg_match

I have a string like this:我有一个这样的字符串:

$string = 'Cache-Control: no-store
Content-Language: en-US-x-lvariant-USA
Vary: Accept-Encoding

{
  "valid" : true,
  "used" : true,
  "isRecycledDomain" : false
}';

And now i want to match "used": true, in that variable.现在我想在那个变量中匹配"used": true, I tried preg_match with this pattern but still not working.我用这种模式尝试了 preg_match 但仍然无法正常工作。

if (preg_match('~\b\"used\" : true,\b~', $string)) {
    //word matched!
} else {
    //not found
}

If you can fix the string, do that..如果您可以修复字符串,请执行此操作..

Else its json with HTTP header which has a standard of 2 new lines then is body which you can split and decode the json into a workable array with a couple of lines. Else its json with HTTP header which has a standard of 2 new lines then is body which you can split and decode the json into a workable array with a couple of lines.

<?php
$string = 'Cache-Control: no-store
Content-Language: en-US-x-lvariant-USA
Vary: Accept-Encoding

{
  "valid" : true,
  "used" : true,
  "isRecycledDomain" : false
}';

$string = explode("\n\n", $string, 2)[1];

$array = json_decode($string, true);

echo $array['valid'];

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

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