I am generating JSON with PHP.
I have been using
$string = 'This string has "double quotes"'; echo addslashes($string);
outputs: This string has \" double quotes\"
Perfectly valid JSON
Unfortunately addslashes also escapes single quotes with catastrophic results for valid JSON
$string = "This string has 'single quotes'"; echo addslashes($string);
outputs: This string has \'single quotes\'
In short, is there a way to only escape double quotes?
The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (') double quote (")
In PHP, people use single quote to define a constant string, like 'a' , 'my name' , 'abc xyz' , while using double quote to define a string contain identifier like "a $b $c $d" .
Try this: str_replace('"', "", $string); str_replace("'", "", $string); Otherwise, go for some regex, this will work for html quotes for example: preg_replace("/<!
Although you should use json_encode
if it’s available to you, you could also use addcslashes
to add \
only to certain characters like:
addcslashes($str, '"\\/')
You could also use a regular expression based replacement:
function json_string_encode($str) { $callback = function($match) { if ($match[0] === '\\') { return $match[0]; } else { $printable = array('"' => '"', '\\' => '\\', "\b" => 'b', "\f" => 'f', "\n" => 'n', "\r" => 'r', "\t" => 't'); return isset($printable[$match[0]]) ? '\\'.$printable[$match[0]] : '\\u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8')))); } }; return '"' . preg_replace_callback('/\\.|[^\x{20}-\x{21}\x{23}-\x{5B}\x{5D}-\x{10FFFF}/u', $callback, $str) . '"'; }
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