Is there a PHP function that only adds slashes to double quotes NOT single quotes

后端 未结 4 1192
Happy的楠姐
Happy的楠姐 2020-12-09 08:06

I am generating JSON with PHP.

I have been using

$string = \'This string has \"double quotes\"\';

echo addslashes($string);

output

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 08:25

    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) . '"';
    }
    

提交回复
热议问题