Search code examples
phpregexpreg-replacepreg-matchpreg-match-all

How to remove the double quotes from json string except the first json value?


Please help me.

Here my json input.

{"id":"FWAX014","price":18,"quantity":1}

Expected output should be like this:

{id:"FWAX014",price:18,quantity:1}

Thanks in advance.


Solution

  • The following regex removes the double quotes you want:

    (?<={|,)"(\w+)"
    

    See the demo

    Explanation

    • (?<={|,) checks that the following pattern is preceded by a curly brace or a comma
    • "(\w+)" matches the word between the quotes

    Example

    $re = '/(?<={|,)"(\w+)"/';
    $str = '{"id":"FWAX014","price":18,"quantity":1}';
    
    $result = preg_replace($re, '$1', $str);