【问题标题】:Handling strings in a file with differnt character encodings (ISO-8859-1 vs UTF-8)处理具有不同字符编码的文件中的字符串(ISO-8859-1 与 UTF-8)
【发布时间】:2012-06-18 13:21:19
【问题描述】:

我在一个文件中有一组行,其中每行可能代表多行 cmets。原始开发人员选择的行分隔符是 pilcrow (¶),因为他认为这永远不会出现在某人的评论中。我现在将它们放入数据库并希望使用更典型的行分隔符(尽管可能由应用程序安装程序设置)。

问题在于,有些行使用 ISO-8859-1 编码(十六进制 b6),而其他行使用 UTF-8 编码(十六进制 c2b6)。我正在寻找一种优雅的方式来处理这个问题,它比我目前正在做的事情有更好的支持。

这是我迄今为止的处理方式,但我宁愿寻找更优雅的解决方案:

// Due to the way the quote file is stored, line breaks can either be
// in 2-byte or 1-byte characters for the pilcrow. Since we're dealing
// with them on a unix system, it makes more sense to replace these
// funky characters with a newline character as is more standard.
//
// To do this, however, requires a bit of chicanery. We have to do
// 1-byte replacement, but with a 2-byte character.
//
// First, some constants:
define('PILCROW', '¶'); // standard two-byte pilcrow character
define('SHORT_PILCROW', chr(0XB6)); // the one-byte version used in the source data some places
define('NEEDLE', '/['.PILCROW.SHORT_PILCROW.']/'); // this is what is searched for
define('REPLACEMENT', $GLOBALS['linesep']);

function fix_line_breaks($quote)
{
  $t0 = preg_replace(NEEDLE,REPLACEMENT,$quote); // convert either long or short pilcrow to a newline. 
  return $t0;
}

【问题讨论】:

  • 混合字符集太糟糕了!我对你有感觉:-(
  • 您为什么不逐行阅读并将数据库中的每一行作为 UTF-8,在 ISO-8859-1 行上使用 utf8_decode 以使它们具有正确的编码?如果将每一行放在不同的记录中,您似乎不需要新的分隔符。
  • @dystroy - 文件的每一行都可能包含多行注释。文件本身的每一行都放入数据库中,但与其在输出上处理混合编码,我宁愿确保它们在输入时保持干净,并保留多行方面。困难是我不知道如何分辨哪些行包含哪个分隔符。
  • 好的。因此,如果您不想更改编码,我不知道有什么比您所做的更好。
  • 如果我理解正确,您仍然需要转换任何编码不正确的行,对吧?

标签: php utf-8 iso-8859-1


【解决方案1】:

我会这样做:

define('PILCROW', '¶'); // standard two-byte pilcrow character
define('REPLACEMENT', $GLOBALS['linesep']);

function fix_encoding($quote) {
    return mb_convert_encoding($quote, 'UTF-8', mb_detect_encoding($quote));
}

function fix_line_breaks($quote) {
    // convert UTF-8 pilcrow to a newline.
    return str_replace(PILCROW, REPLACEMENT, $quote);
}

对于每行注释,调用fix_encoding 然后fix_line_breaks

$quote = fix_encoding($quote);
$quote = fix_line_breaks($quote);

【讨论】:

  • 哦,我喜欢,谢谢。我刚想出类似的东西。我想通了另一种方式,转换 UTF-8 字符串,但这可能会更好。有趣的是,当我在 8859 版本上运行 mb_detect_encoding 时,它返回一个空字符串。
  • 好的,稍作改动。 mb_detect_encoding 返回 FALSE,因此该函数需要检查并替换 ISO-8859-1(如果是)。它有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多