[ACCEPTED]-Is there a PHP function that only adds slashes to double quotes NOT single quotes-json
Although you should use json_encode
if it’s available 3 to you, you could also use addcslashes
to add \
only 2 to certain characters like:
addcslashes($str, '"\\/')
You could also 1 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) . '"';
}
Is there a PHP function that only adds slashes 10 to double quotes NOT single quotes
There 9 is no function like addslashes()
that only adds a slash 8 to double quotes.
However you can make use 7 of addcslashes()
to only add slashes to specific characters, e.g. only to 6 double quotes:
addcslashes($string, '"');
That does exactly as described. If 5 you want to have it compatible with stripcslashes()
however, you 4 need to add the slash itself to the list 3 of chars:
addcslashes($string, '"\\');
That should do the job you've been 2 asking for. I have no idea if that is compatible 1 with json encoding.
function json_string_encode( $str ) {
$from = array('"'); // Array of values to replace
$to = array('\\"'); // Array of values to replace with
// Replace the string passed
return str_replace( $from, $to, $str );
}
To use the function you simply need to use
$text = json_string_encode($text);
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.