是否有一个PHP函数仅将斜杠添加到双引号而不是单引号 [英] Is there a PHP function that only adds slashes to double quotes NOT single quotes

查看:114
本文介绍了是否有一个PHP函数仅将斜杠添加到双引号而不是单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PHP生成JSON.

I am generating JSON with PHP.

我一直在使用

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

echo addslashes($string);

输出:This string has \" double quotes\"

完全有效的JSON

不幸的是,加号也使有效JSON的单引号具有灾难性的结果

$string = "This string has 'single quotes'";

echo addslashes($string);

输出:This string has \'single quotes\'

简而言之,有没有一种方法只能转义双引号?

In short, is there a way to only escape double quotes?

推荐答案

如果您应该使用 json_encode 它可供您使用,您也可以使用 addcslashes 仅将\添加到某些字符,例如:

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

这篇关于是否有一个PHP函数仅将斜杠添加到双引号而不是单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆