2012-03-06 34 views
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('&#146;'); 

回答

5

html_entity_decode已經這樣做了,你在找什麼:

$string = '&#146;'; 

echo html_entity_decode($string, ENT_COMPAT, 'UTF-8'); 

它將返回字符:

’ binary hex: c292 

這是PRIVATE USE TWO (U+0092)。由於它是私人使用,所以您的 PHP配置/版本/編譯可能根本不會返回它。

也有一些更多的怪癖:

但在HTML(而不是XHTML,它使用XML規則等),這是一個長期的瀏覽器怪癖&#128;&#159;被誤解爲範圍內的字符引用表示與Windows西文代碼頁(cp1252)中的字節128到159相關的字符,而不是具有這些代碼點的Unicode字符。 HTML5標準最終記錄了這種行爲。

參見:&#146; is getting converted as 「\u0092」 by nokogiri in ruby on rails

+1

試圖與剛剛html_entity_decode但是,這並不工作,它返回空爲好。不知道你在說什麼空間,我的代碼中沒有空間?我也嘗試刪除html_entity_decode或將其作爲最後一個執行,但沒有幫助。謝謝。 – Wesley 2012-03-06 16:34:48

+0

@韋斯利:根據你的PHP版本,'html_entity_decode'確實會返回一些東西。不過,我已經擴大了可能會更多的一些亮點的答案。 – hakre 2012-03-06 16:38:28

+0

此外[這個[轉換(doublebyte)字符串爲十六進制]](http://stackoverflow.com/a/7015137/367456)可能會有所幫助。 – hakre 2012-03-06 16:39:42