了解 PHP mb_detect_encoding 和 mb_check_encoding 函数的结果

Dom*_*Dom 6 php character-encoding windows-1252

我试图理解两个函数mb_detect_encoding和的逻辑mb_check_encoding,但文档很差。从一个非常简单的测试字符串开始

$string = "\x65\x92";
Run Code Online (Sandbox Code Playgroud)

使用 Windows-1252 编码时,它是小写“a”,后跟大引号。

我得到以下结果:

mb_detect_encoding($string,"Windows-1252"); // false
mb_check_encoding($string,"Windows-1252"); // true
mb_detect_encoding($string,"ISO-8859-1"); // ISO-8859-1
mb_check_encoding($string,"ISO-8859-1"); // true
mb_detect_encoding($string,"UTF-8",true); // false
mb_detect_encoding($string,"UTF-8"); // UTF-8
mb_check_encoding($string,"UTF-8"); // false
Run Code Online (Sandbox Code Playgroud)

Mic*_*ler 2

您的示例很好地说明了为什么mb_detect_encoding应该谨慎使用,因为它不直观,有时在逻辑上是错误的。如果必须使用,请始终作为第三个参数传入strict = true(因此非 UTF8 字符串不会被报告为 UTF-8。

mb_check_encoding按照可能性/优先级的顺序运行一系列所需的编码会更可靠一些。例如:

$encodings = [
    'UTF-8',
    'Windows-1252',
    'SJIS',
    'ISO-8859-1',
];

$encoding = 'UTF-8';
$string = 'foo';
foreach ($encodings as $encoding) {
    if (mb_check_encoding($string, $encoding)) {
        // We'll assume encoding is $encoding since it's valid
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

不过,顺序取决于您的优先级。