我用PHP生成JSON.
我一直在用
$string = 'This string has "double quotes"';
echo addslashes($string);
Run Code Online (Sandbox Code Playgroud)
输出: This string has \" double quotes\"
完全有效的JSON
不幸的是,对于有效的JSON,addslashes也会逃避单引号,带来灾难性后果
$string = "This string has 'single quotes'";
echo addslashes($string);
Run Code Online (Sandbox Code Playgroud)
输出: This string has \'single quotes\'
简而言之,有没有办法只能逃避双引号?
Gum*_*mbo 52
虽然您应该使用json_encode它,但您也可以使用它addcslashes来添加\到某些字符,如:
addcslashes($str, '"\\/')
Run Code Online (Sandbox Code Playgroud)
您还可以使用基于正则表达式的替换:
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) . '"';
}
Run Code Online (Sandbox Code Playgroud)
hak*_*kre 15
是否有一个PHP函数只添加斜杠到双引号而不是单引号
没有这样的功能addslashes()只会在双引号中添加斜杠.
但是,您可以使用addcslashes()仅向特定字符添加斜杠,例如仅添加双引号:
addcslashes($string, '"');
Run Code Online (Sandbox Code Playgroud)
完全如上所述.stripcslashes()但是,如果要使其兼容,则需要将斜杠本身添加到字符列表中:
addcslashes($string, '"\\');
Run Code Online (Sandbox Code Playgroud)
那应该做你一直要求的工作.我不知道这是否与json编码兼容.
| 归档时间: |
|
| 查看次数: |
29243 次 |
| 最近记录: |