【问题标题】:Understanding results of PHP's mb_detect_encoding and mb_check_encoding functions了解 PHP 的 mb_detect_encoding 和 mb_check_encoding 函数的结果
【发布时间】:2016-10-07 14:55:11
【问题描述】:

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

$string = "\x65\x92";

在使用 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
  • 我不明白为什么mb_detect_encoding 为字符串提供“ISO-8859-1”而不是“Windows-1252”,当根据https://en.wikipedia.org/wiki/ISO/IEC_8859-1 和https://en.wikipedia.org/wiki/Windows-1252 定义字节x92在 Windows-1252 字符编码中,但不在 ISO-8859-1 中。

  • 其次,我不明白mb_detect_encoding 是如何返回false,但mb_check_encoding 可以返回true 以获得相同的字符串和相同的字符编码。

  • 最后,我不明白为什么字符串可以被检测为 UTF-8,无论是否是严格模式。字节 x92 是 UTF-8 中的延续字节,但在此字符串中,它跟在有效字符字节之后,而不是序列的前导字节。

【问题讨论】:

  • 偶然发现这个问题很有趣。我是 PHP 8.0/8.1 中这些函数的新实现的作者。我想你会发现他们现在的行为更加一致。如果您还有任何问题,请随时问我。

标签: php character-encoding windows-1252


【解决方案1】:

您的示例很好地说明了为什么应该谨慎使用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;
    }
}

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

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多