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>"}
To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", "");
if you want to escape double quote in JSON use \\ to escape it.
Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .
Single quoted ¶The simplest way to specify a string is to enclose it in single quotes (the character ' ). To specify a literal single quote, escape it with a backslash ( \ ). To specify a literal backslash, double it ( \\ ).
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>"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With