Search code examples
phpregexpreg-split

How can I find a string in a JSON string using a regular expression on PHP?


I have string with hyphens:

$str = `Res TP/1.1 101 Switching Protocols
Upgrade: websocket
Sec-WebSocket-Version: 13
Connection: Upgrade
Sec-WebSocket-Accept: dlnHlWqQ4h57DuALMOjKJmxbNn8=
Server: workerman/4.1.9

rec{"result":1}len14`

How can I extract a substring {"result":1} from this string?


Solution

  • If you only have 1 JSON block (and no other {} symbols) in your string

    $str = 'Res TP/1.1 101 Switching Protocols
    Upgrade: websocket
    Sec-WebSocket-Version: 13
    Connection: Upgrade
    Sec-WebSocket-Accept: dlnHlWqQ4h57DuALMOjKJmxbNn8=
    Server: workerman/4.1.9
    
    rec{"result":1}len14';
    
    $pattern = '[{(.*)}]';
    
    if (preg_match($pattern, $str, $matches)) {    
        print_r($matches);    
    }
    
    print_r(json_decode($matches[0]));
    

    Result is

    > Array
    (
        [0] => {"result":1}
        [1] => "result":1
    )
    

    So $matches[0] contains your JSON data which can be decoded to create an object

    stdClass Object
    (
        [result] => 1
    )