Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace double quotes with single quotes in json string in php

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>"}
like image 737
ferhado Avatar asked Aug 28 '18 04:08

ferhado


People also ask

How can I replace double quotes in a string in PHP?

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("^\"|\"$", "");

How do I ignore double quotes in JSON?

if you want to escape double quote in JSON use \\ to escape it.

Can JSON strings use single quotes?

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 .

Can you use single quotes for strings in PHP?

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 ( \\ ).


1 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>"}
like image 79
Florian Avatar answered Nov 07 '22 13:11

Florian