PHP:检查字符串是否为utf-8或utf-16le

时间:2018-03-29 00:53:41

标签: php utf-8 utf-16le mb-convert-encoding

我正在编写默认返回utf-8文件的函数,如果你提供特殊参数,它将返回utf-16le中的内容。我开始为这个函数编写单元测试,我不明白的是如何检查编码是“utf-8”还是“utf-16le”。我已尝试mb_detect_encoding,但即使在此代码段中也会返回false

  $utf16Doc = mb_convert_encoding($doc, "utf-16le", "utf8");
  $test = mb_detect_encoding($utf16Doc, "utf-16le");
  var_dump($test);

感谢任何想法如何检查编码是utf-16le而不是utf-8。

1 个答案:

答案 0 :(得分:2)

通过BOM检测文件的UTF-8/16/32的简单方法(不使用字符串或没有BOM的文件)

<?php
// Unicode BOM is U+FEFF, but after encoded, it will look like this.
define ('UTF32_BIG_ENDIAN_BOM'   , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM'   , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM'               , chr(0xEF) . chr(0xBB) . chr(0xBF));

function detect_utf_encoding($filename) {

    $text = file_get_contents($filename);
    $first2 = substr($text, 0, 2);
    $first3 = substr($text, 0, 3);
    $first4 = substr($text, 0, 3);

    if ($first3 == UTF8_BOM) return 'UTF-8';
    elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
    elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
    elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
    elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
}
?>

所以现在你可以尝试这样,

 $utf16Doc = mb_convert_encoding($doc, "utf-16le", "utf8");
 $test = detect_utf_encoding($utf16Doc);
 var_dump($test);

明确陈述:这不是我自己的书面答复。我刚刚在用户http://php.net/manual/en/function.mb-detect-encoding.php#68607mb_detect_encoding下的php.net官方网站上找到了它。希望这会以某种方式帮助你