我正在尝试将字符(如 À)转换为其转义形式,例如 \u00c0
.我知道这可以用 json_encode
来完成, 但该函数将反斜杠添加到特殊字符。 (我其实并不希望得到一个json对象,只是字符串转换):
$str = 'À ß \ Ć " Ď < Ĕ';
对于上面的字符串,它会返回
$str = '\u00c0 \u00df \\ \u0106 \" \u010e < \u0114';
如果我 stripslashes
, 它也会去掉每个 uxxxx
之前的那个.
是否有针对此特定转换的函数?或者最简单的方法是什么?
最佳答案
你可以使用下面的代码来回退
代码:
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) "我好"
关于php - 将 Unicode 字符转换为 "\uxxxx"形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13614796/