尽管您应该使用
json_enpre可用的字符,但也
addcslashes可以仅将其添加到某些字符,例如:
addcslashes($str, '"\/')
您还可以使用基于正则表达式的替换:
function json_string_enpre($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) . '"';}


