这个问题看起来简单得令人尴尬,但我一直没能找到答案。
下面这行C#代码的PHP等价物是什么?
string str = "\u1000";
此示例创建一个包含单个Unicode字符的字符串,该字符的"Unicode numeric value“为十六进制的1000
(十进制的4096
)。
也就是说,在PHP中,我如何创建包含一个Unicode字符的字符串,该字符的Unicode数值是已知的?
发布于 2011-05-19 20:20:39
因为JSON直接支持\uxxxx
语法,所以我想到的第一件事是:
$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');
另一种选择是使用mb_convert_encoding()
echo mb_convert_encoding('က', 'UTF-8', 'HTML-ENTITIES');
或者利用UTF-16BE (大端)和Unicode代码点之间的直接映射:
echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');
发布于 2015-12-22 05:46:35
PHP7.0.0引入了"Unicode codepoint escape" syntax。
现在可以通过使用double-quoted或heredoc字符串轻松地编写Unicode字符,而无需调用任何函数。
$unicodeChar = "\u{1000}";
发布于 2011-05-19 20:59:29
PHP不知道这些Unicode转义序列。但由于未知转义序列不受影响,您可以编写自己的函数来转换此类Unicode转义序列:
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}
或者使用anonymous function expression代替create_function
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
}, $str);
}
它的用法:
$str = unicodeString("\u1000");
https://stackoverflow.com/questions/6058394
复制相似问题