【发布时间】:2014-03-24 22:01:04
【问题描述】:
我正在尝试将 php 字符串从 utf-8 解码为所需的编码 (iso-8859-2)。问题是,utf-8 字符串包含不适合 iso-8859-2 的字符,但从 windows-1251 转换为 utf-8(尽管它们看起来与 ISO-8859 的原生字符完全相同- 2)。这些字符由“?”表示在输出上。
如果我尝试将相同的字符串转换为 windows-1251,则会出现相同的字符,但丢失的字符分别是 iso-8859-2 的原生字符(如“ä”、“ö”等)
我从 mysql 数据库中获取字符串,需要转换为非 unicode 字符集并将它们存储到 sqlite 数据库文件中,因为要使用它们的程序不支持 unicode。
那么,我的问题是,有没有办法为 utf-8 中的字符获取可能的非 unicode 编码?我目前正在遍历整个 utf 字符串并尝试逐个解码每个字符,但 windows-1251 字符仍然丢失。
代码如下:
$string = "various charset input";
$str = str_split_unicode($string,1); // The function from the php-str_split manual page, splits utf string into an array
$handler = "";
foreach($str as $value):
$currentChar = iconv("utf-8", "iso-8859-2", $value) or "%no%";
if($currentChar == "%no%" ):
$currentChar = "";
$currentChar = iconv("utf-8", "windows-1251", $value) or "%no%";
endif;
if($currentChar != "%no%"):
$handler .= $currentChar;
else:
$handler .= $value;
endif;
endforeach;
$string = $handler;
但问号还在。
更新
感谢 CertaiN,我编辑了您提供的函数(虽然它可能变得不那么可读了),因此它将字符转换回适当的编码。
功能
function utf8_to_multicharset($str, $encoding, $htmSupportedOutput="iso-8859-15") {
$utf8 = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
$out = $utf8;
mb_convert_variables($encoding, 'UTF-8', $out);
is_array($htmSupportedOutput) or $htmSupportedOutput = explode(",",$htmSupportedOutput);
$table = get_html_translation_table(HTML_SPECIALCHARS | ENT_QUOTES);
foreach ($out as $i => &$char) {
if ($char === '?' && $utf8[$i] !== '?') {
$char = mb_convert_encoding($utf8[$i], 'HTML-ENTITIES', 'UTF-8');
}
elseif (isset($table[$char])) {
$char = $table[$char];
}
foreach($htmSupportedOutput as $o):
$char = html_entity_decode($char,null,$o);
endforeach;
}
return implode('', $out);
}
现在它从指定编码列表中检查并将字符串转换为支持它的编码,如下所示:
示例
PHP 使用情况:
<?php
$string = "vatiöus charset иnput";
$result = utf8_to_multicharset($string,"iso-8859-2","cp1252,cp1251,koi8r");
?>
【问题讨论】: