我正在用PHP生成JSON。
我一直在使用
$string = 'This string has "double quotes"';
echo addslashes($string);
输出:This string has '" double quotes'"
完全有效的JSON
不幸的是,对于有效的JSON,addslashes也会转义单引号,从而导致灾难性的结果
$string = "This string has 'single quotes'";
echo addslashes($string);
输出:This string has ''single quotes''
简而言之,有没有一种方法可以只转义双引号?
尽管您应该使用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) . '"';
}
有没有一个PHP函数只在双引号而不是单引号中添加斜杠
没有像addslashes()
这样的函数只在双引号中添加斜线。
但是,您可以使用addcslashes()
仅向特定字符添加斜杠,例如仅向双引号添加斜杠:
addcslashes($string, '"');
这完全符合描述。然而,如果你想让它与stripcslashes()
兼容,你需要将斜杠本身添加到字符列表中:
addcslashes($string, '"''');
这应该能完成你一直要求的工作。我不知道这是否与json编码兼容。
如果您正在生成JSON,为什么不直接使用json_encode()
函数呢?
function json_string_encode( $str ) {
$from = array('"'); // Array of values to replace
$to = array('''"'); // Array of values to replace with
// Replace the string passed
return str_replace( $from, $to, $str );
}
要使用该功能,只需使用
$text = json_string_encode($text);