3
我有這段代碼將數字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但是,這並不工作,它返回空爲好。不知道你在說什麼空間,我的代碼中沒有空間?我也嘗試刪除html_entity_decode或將其作爲最後一個執行,但沒有幫助。謝謝。 – Wesley 2012-03-06 16:34:48
@韋斯利:根據你的PHP版本,'html_entity_decode'確實會返回一些東西。不過,我已經擴大了可能會更多的一些亮點的答案。 – hakre 2012-03-06 16:38:28
此外[這個[轉換(doublebyte)字符串爲十六進制]](http://stackoverflow.com/a/7015137/367456)可能會有所幫助。 – hakre 2012-03-06 16:39:42