我正在用PHP生成JSON。
我一直在用
$string = 'This string has "double quotes"'; echo addslashes($string);
输出: This string has \" double quotes\"
This string has \" double quotes\"
完全有效的JSON
不幸的是,addslashes还会对有效JSON的灾难性结果进行单引号转义
$string = "This string has 'single quotes'"; echo addslashes($string);
输出: This string has \'single quotes\'
This string has \'single quotes\'
简而言之,是否有一种方法只能转义双引号?
尽管您应该使用json_encode可用的字符,但也addcslashes可以\仅将其添加到某些字符,例如:
json_encode
addcslashes
\
addcslashes($str, '"\\/')
您还可以使用基于正则表达式的替换:
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) . '"'; }