I need to remove "-s that making invalid json, how do I do it in php regex?
"name": "Steak "au Four" ",
in this situation remove "au Four"-s " quotes
This is the php code to match the two quotes within a quote:
$re = "/^\"name\": \"[^\"]*?(\")*?[^\"]*?(\")*?[^\"]*?\"$/";
$str = "\"Steak \"au Four\" \"";
preg_match($re, $str, $matches);
There's no use of matching the quotes with regex for replacing, because the only thing you will end up with is the quotes themselves.
Actually, that is not quite true, as you can get them along with indexes by passing PREG_OFFSET_CAPTURE
as the forth parameter to the preg_match()
(you can see in the documentation).
But again, what if there's more than two double quotes. In that case the regex will be more complicated. Then you will have transform the string to the array with str_split()
, so you can unset elements by index. And finally transform array to string again with join()
or implode()
by joining the elements together.
I think easier to grab the whole value and then replace the quotes with str_replace()
. In you case you can do something like this:
$jsonLine = "\"name\":\"Steak \"au Four\" \"";
$jsonLine = trim($jsonLine);
$pattern = '/^(?P<name>"name"\s*:\s*)(?P<value>".*".*")$/';
if (preg_match($pattern, $jsonLine, $matches) === false) {
exit('Pattern not matched');
}
$name = $matches['name'];
$value = trim(str_replace('"', '', $matches['value']));
$newJsonLine = "$name\"$value\"";
echo $newJsonLine;
You can see the demo here.