如果将 utf8_encode() 应用于已经是 UTF8 的字符串,它将返回一个乱码的 UTF8 输出。
我创建了一个函数来解决所有这些问题。它叫做 forceUTF8()。
你不需要知道你的字符串的编码是什么。它可以是 Latin1 (iso 8859-1) 或 UTF8,或者字符串可以是两者的混合。 forceUTF8() 会将所有内容都转换为 UTF8。
我这样做是因为一项服务向我提供了一个混乱的数据源,将 UTF8 和 Latin1 混合在同一个字符串中。
用法:
$utf8_string = forceUTF8($utf8_or_latin1_or_mixed_string);
$latin1_string = forceLatin1($utf8_or_latin1_or_mixed_string);
我添加了另一个函数 fixUFT8(),它将修复每个看起来乱码的 UTF8 字符串。
用法:
$utf8_string = fixUTF8($garbled_utf8_string);
例子:
echo fixUTF8("Fédération Camerounaise de Football");
echo fixUTF8("Fédération Camerounaise de Football");
echo fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo fixUTF8("Fédération Camerounaise de Football");
将输出:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
更新:我将 theese 转换为静态类,它们现在住在 Github:
https://github.com/neitanod/forceutf8