如何将Unicode字符串为HTML实体转换? ( HEX不十进制)
例如,转换Français ,以Français 。
Answer 1:
你的字符串看起来像UCS-4编码你可以试试
$first = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($m) {
$char = current($m);
$utf = iconv('UTF-8', 'UCS-4', $char);
return sprintf("%s;", ltrim(strtoupper(bin2hex($utf)), "0"));
}, $string);
产量
string 'Français' (length=13)
Answer 2:
对于十六进制编码在缺少相关的问题 :
$output = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($match) {
list($utf8) = $match;
$binary = mb_convert_encoding($utf8, 'UTF-32BE', 'UTF-8');
$entity = vsprintf('%X;', unpack('N', $binary));
return $entity;
}, $input);
这类似于使用@巴巴的回答UTF-32BE ,然后unpack和vsprintf的格式需求。
如果你喜欢iconv了mb_convert_encoding ,这是类似的:
$output = preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($match) {
list($utf8) = $match;
$binary = iconv('UTF-8', 'UTF-32BE', $utf8);
$entity = vsprintf('%X;', unpack('N', $binary));
return $entity;
}, $input);
我觉得这个字符串操作中有点更加清晰然后HTML实体获取十六进制编码 。
Answer 3:
首先,当我最近面临这个问题,我解决它通过确保我的代码,文件,数据库连接,数据库表都是UTF-8之后,简单地呼应文字工作。 如果必须逃脱从数据库中使用的输出htmlspecialchars()而不是htmlentities()使得UTF-8符号孤独和没有离开试图逃脱。
想是因为它解决了类似的问题,我记录的替代解决方案。 我在使用PHP的utf8_encode()逃跑“特殊”字符。
我想将它们转换成HTML实体显示,我写了这个代码,因为我想避免的iconv或这样的功能尽可能因为并不是所有的环境一定有他们(你纠正我,如果不是这样!)
$foo = 'This is my test string \u03b50';
echo unicode2html($foo);
function unicode2html($string) {
return preg_replace('/\\\\u([0-9a-z]{4})/', '$1;', $string);
}
希望这可以帮助有需要的人:-)
Answer 4:
请参阅如何从Unicode代码点的字符在PHP? 对于一些代码,可以让你做到以下几点:
使用示例 :
echo "Get string from numeric DEC value\n";
var_dump(mb_chr(50319, 'UCS-4BE'));
var_dump(mb_chr(271));
echo "\nGet string from numeric HEX value\n";
var_dump(mb_chr(0xC48F, 'UCS-4BE'));
var_dump(mb_chr(0x010F));
echo "\nGet numeric value of character as DEC string\n";
var_dump(mb_ord('ď', 'UCS-4BE'));
var_dump(mb_ord('ď'));
echo "\nGet numeric value of character as HEX string\n";
var_dump(dechex(mb_ord('ď', 'UCS-4BE')));
var_dump(dechex(mb_ord('ď')));
echo "\nEncode / decode to DEC based HTML entities\n";
var_dump(mb_htmlentities('tchüß', false));
var_dump(mb_html_entity_decode('tchüß'));
echo "\nEncode / decode to HEX based HTML entities\n";
var_dump(mb_htmlentities('tchüß'));
var_dump(mb_html_entity_decode('tchüß'));
echo "\nUse JSON encoding / decoding\n";
var_dump(codepoint_encode("tchüß"));
var_dump(codepoint_decode('tch\u00fc\u00df'));
输出 :
Get string from numeric DEC value
string(4) "ď"
string(2) "ď"
Get string from numeric HEX value
string(4) "ď"
string(2) "ď"
Get numeric value of character as DEC int
int(50319)
int(271)
Get numeric value of character as HEX string
string(4) "c48f"
string(3) "10f"
Encode / decode to DEC based HTML entities
string(15) "tchüß"
string(7) "tchüß"
Encode / decode to HEX based HTML entities
string(15) "tchüß"
string(7) "tchüß"
Use JSON encoding / decoding
string(15) "tch\u00fc\u00df"
string(7) "tchüß"
文章来源: convert unicode to html entities hex
596

被折叠的 条评论
为什么被折叠?



