Replace double quotes with single quotes in json string in php

Viewed 4357

I have a json string which contains some html and it's attrubutes. I'm trying to to escape or replace double quotes with single quotes in this string. my code works with some html attributes but not with all.

My example:

$json='{"en":"<b class="test" size="5" >Description</b>"}';
$json=preg_replace('/([^:,{])"([^:,}])/', "$1".'\''."$2",$json);
echo htmlspecialchars($json);
//ouput: {"en":"<b class='test' size='5" >Description</b>"}


Needed result:

{"en":"<b class='test' size='5' >Description</b>"}
2 Answers

I hope this works as expected ([^{,:])"(?![},:])

$json='{"en":"<b class="test" size="5" >Description</b>"}';
$json=preg_replace('/([^{,:])"(?![},:])/', "$1".'\''."$2",$json);

Results in

{"en":"<b class='test' size='5' >Description</b>"}

Try this one : str_replace('"', "'",$json);

$json='{"en":"<b class="test" size="5" >Description</b>"}';
$json=str_replace('"', "'",$json);
echo htmlspecialchars($json);

Output will : {'en':'<b class='test' size='5' >Description</b>'}

Related