Search code examples
phppreg-match

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. I tried preg_match with this pattern but still not working.

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

Solution

  • 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.

    <?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'];