2013-04-05 33 views
4

我試圖檢測字符串的字符編碼,但我無法得到正確的結果。
例如:在PHP中檢測正確的字符編碼?

$str = "€ ‚ ƒ „ …" ; 
$str = mb_convert_encoding($str, 'Windows-1252' ,'HTML-ENTITIES') ; 
// Now $str should be a Windows-1252-encoded string. 
// Let's detect its encoding: 
echo mb_detect_encoding($str,'Windows-1252, ISO-8859-1, UTF-8') ; 

即代碼輸出ISO-8859-1但它應該是Windows-1252

這是怎麼回事?

編輯:
更新的示例,以迴應@ raina77ow。

$str = "€‚ƒ„…" ; // no white-spaces 
$str = mb_convert_encoding($str, 'Windows-1252' ,'HTML-ENTITIES') ; 
$str = "Hello $str" ; // let's add some ascii characters 
echo mb_detect_encoding($str,'Windows-1252, ISO-8859-1, UTF-8') ; 

我再次得到錯誤的結果。

+0

什麼是您使用的PHP版本?它在這裏顯示正確http://codepad.viper-7.com/NfvdWm。順便說一句,你應該總是首先列出UTF-8,因爲它是最受限制的。可能根本不需要ISO-8859-1,因爲任何東西都是有效的ISO-8859-1。 – Esailija 2013-04-06 09:25:55

+0

@Esailija,你沒有使用問題中任何兩個例子的代碼。試試這兩個例子中的任何一個,你就會得到結果'ISO-8859-1'。 – GetFree 2013-04-07 01:17:10

回答

0

雖然與ISO-8859-1和CP-1252編碼字符串有不同的字節碼錶示:

<?php 
$str = "&euro; &sbquo; &fnof; &bdquo; &hellip;" ; 
foreach (array('Windows-1252', 'ISO-8859-1') as $encoding) 
{ 
    $new = mb_convert_encoding($str, $encoding, 'HTML-ENTITIES'); 
    printf('%15s: %s detected: %10s explicitly: %10s', 
     $encoding, 
     implode('', array_map(function($x) { return dechex(ord($x)); }, str_split($new))), 
     mb_detect_encoding($new), 
     mb_detect_encoding($new, array('ISO-8859-1', 'Windows-1252')) 
    ); 
    echo PHP_EOL; 
} 

結果:

Windows-1252: 802082208320842085 detected:   explicitly: ISO-8859-1 
    ISO-8859-1: 3f203f203f203f203f detected:  ASCII explicitly: ISO-8859-1 

...從我們可以在這裏看到它看起來像mb_detect_encoding的第二參數有問題。使用mb_detect_order而不是參數產生非常相似的結果。

+0

示例中的字符在ISO-8859-1中不存在。 – GetFree 2013-04-05 22:04:27

+0

我列表中的第一個匹配編碼是'Windows-1252'。 「ISO-8859-1」是列表中的第二位。 – GetFree 2013-04-05 22:23:33

+1

@GetFree php字符串不是字符,而是字節。任何PHP字符串都是有效的「ISO-8859-1」,因爲任何字節都是有效的ISO-8859-1。 – Esailija 2013-04-06 09:24:36

1

PHP中Windows-1252的問題在於,它幾乎可以檢測到從不,因爲只要您的文本包含0x80到0x9f以外的任何字符,它就不會被檢測爲Windows-1252。

這意味着如果你的字符串包含一個普通的ASCII字母,如「A」,甚至空格字符,PHP會說這是無效的Windows-1252,在你的情況下,回退到下一個可能的編碼,這是ISO 8859-1。這是一個PHP錯誤,請參閱https://bugs.php.net/bug.php?id=64667