4

我正在尝试将字符(例如 À)转换为转义形式,例如\u00c0. 我知道这可以用 来完成json_encode,但是该函数会为特殊字符添加反斜杠。(我实际上并不希望得到一个 json 对象,只是字符串转换):

$str = 'À ß \ Ć " Ď < Ĕ';

对于上面的字符串,它将返回

$str = '\u00c0 \u00df \\ \u0106 \" \u010e < \u0114';

如果是我stripslashes,它也会在每个之前剥离一个uxxxx

这种特定转换是否有功能?或者最简单的方法是什么?

4

4 回答 4

3

您可以使用以下代码来回前进

代码

if (!function_exists('codepoint_encode')) {
    function codepoint_encode($str) {
        return substr(json_encode($str), 1, -1);
    }
}

if (!function_exists('codepoint_decode')) {
    function codepoint_decode($str) {
        return json_decode(sprintf('"%s"', $str));
    }
}

如何使用

echo "\nUse JSON encoding / decoding\n";
var_dump(codepoint_encode("我好"));
var_dump(codepoint_decode('\u6211\u597d'));

输出

Use JSON encoding / decoding
string(12) "\u6211\u597d"
string(6) "我好"
于 2015-11-25T00:45:28.273 回答
1
$str = 'À ß \ Ć " Ď < Ĕ';

echo trim(preg_replace('/\\\\([^u])/', "$1", json_encode($str)), '"');
// ouptuts: \u00c0 \u00df \ \u0106 " \u010e < \u0114

I know it uses json_encode(), but it's the easiest way to convert to \uXXXX

于 2012-11-28T21:39:00.660 回答
0

对@cryptic 的回答稍作修改:

脚本

$str = 'À ß \ Ć " Ď < Ĕ \\\\uxxx';
echo trim(preg_replace('/\\\\([^u])/', "$1", json_encode($string, JSON_UNESCAPED_SLASHES)), '"');

输出

\u00c0 \u00df \ \u0106 " \u010e < \u0114 \\uxxx
于 2012-11-28T21:54:25.457 回答
0
function convertChars($str) {
    return json_decode("\"$str\"");
}
于 2015-04-23T12:34:21.370 回答