Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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', "f" => 'f', "
" => 'n', "
" => 'r', "" => '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) . '"';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...