通过PHP解码数字html实体
问题描述:
我有这段代码将数字html实体解码为UTF8等效字符。通过PHP解码数字html实体
我想这个角色转换:
’
这应该输出:
然而,就这样消失(没有输出)。 (我已经检查了页面的源代码,页面有正确的utf8字符集标题/元标记)。
有人知道代码有什么问题吗?
function entity_decode($string, $quote_style = ENT_COMPAT, $charset = "UTF-8") {
$string = html_entity_decode($string, $quote_style, $charset);
$string = preg_replace_callback('~&#x([0-9a-fA-F]+);~i', "chr_utf8_callback", $string);
$string = preg_replace('~&#([0-9]+);~e', 'chr_utf8("\\1")', $string);
//this is another method, which also doesn't work..
//$string = preg_replace_callback("/(\&#[0-9]+;)/", "entity_decode_callback", $string);
return $string;
}
function chr_utf8_callback($matches) {
return chr_utf8(hexdec($matches[1]));
}
function chr_utf8($num) {
if ($num < 128) return chr($num);
if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
return '';
}
function entity_decode_callback($m) {
return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES");
}
echo '=' . entity_decode('’');
答
html_entity_decode
已经这样做了,你在找什么:
$string = '’';
echo html_entity_decode($string, ENT_COMPAT, 'UTF-8');
它将返回字符:
’ binary hex: c292
这是PRIVATE USE TWO (U+0092)。由于它是私人使用,所以您的 PHP配置/版本/编译可能根本不会返回它。
也有一些更多的怪癖:
但在HTML(而不是XHTML,它使用XML规则等),这是一个长期的浏览器怪癖
€
到Ÿ
被误解为范围内的字符引用表示与Windows西文代码页(cp1252)中的字节128到159相关的字符,而不是具有这些代码点的Unicode字符。 HTML5标准最终记录了这种行为。
参见:’ is getting converted as “\u0092” by nokogiri in ruby on rails
试图与刚刚html_entity_decode但是,这并不工作,它返回空为好。不知道你在说什么空间,我的代码中没有空间?我也尝试删除html_entity_decode或将其作为最后一个执行,但没有帮助。谢谢。 – Wesley 2012-03-06 16:34:48
@韦斯利:根据你的PHP版本,'html_entity_decode'确实会返回一些东西。不过,我已经扩大了可能会更多的一些亮点的答案。 – hakre 2012-03-06 16:38:28
此外[这个[转换(doublebyte)字符串为十六进制]](http://*.com/a/7015137/367456)可能会有所帮助。 – hakre 2012-03-06 16:39:42