iconv 函数
参见
目录
- iconv_get_encoding — 获取 iconv 扩展的内部配置变量
- iconv_mime_decode_headers — 一次性解码多个 MIME 头字段
- iconv_mime_decode — 解码一个MIME头字段
- iconv_mime_encode — Composes a MIME header field
- iconv_set_encoding — 为字符编码转换设定当前设置
- iconv_strlen — 返回字符串的字符数统计
- iconv_strpos — Finds position of first occurrence of a needle within a haystack
- iconv_strrpos — Finds the last occurrence of a needle within a haystack
- iconv_substr — 截取字符串的部分
- iconv — 字符串按要求的字符编码来转换
- ob_iconv_handler — 以输出缓冲处理程序转换字符编码

User Contributed Notes 2 notes
Martin Petrov ¶
12 years ago
This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.
<?php
function cp1251_to_utf8($s)
{
if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
{
$c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
for($i=0; $i<strlen($s); $i++)
{
$c=ord($s[$i]);
if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
elseif ($c>239) $t.=$c209.chr($c-112);
elseif ($c==184) $t.=$c209.$c209;
elseif ($c==168) $t.=$c208.$c129;
else $t.=$s[$i];
}
return $t;
}
else
{
return $s;
}
}
function utf8_to_cp1251($s)
{
if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "UTF-8")
{
for ($c=0;$c<strlen($s);$c++)
{
$i=ord($s[$c]);
if ($i<=127) $out.=$s[$c];
if ($byte2)
{
$new_c2=($c1&3)*64+($i&63);
$new_c1=($c1>>2)&5;
$new_i=$new_c1*256+$new_c2;
if ($new_i==1025)
{
$out_i=168;
} else {
if ($new_i==1105)
{
$out_i=184;
} else {
$out_i=$new_i-848;
}
}
$out.=chr($out_i);
$byte2=false;
}
if (($i>>5)==6)
{
$c1=$i;
$byte2=true;
}
}
return $out;
}
else
{
return $s;
}
}
?>
nod at mobi dot kz ¶
15 years ago
If you need convert string from Windows-1251 to 866. Some characters of 1251 haven't representation on DOS 866. For example, long dash -- chr(150) will be converted to 0, after that iconv finish his work and other charactes will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).
Use this:
//$text - input text in windows-1251
//$cout - output text in 866 (cp866, dos ru ascii)
for($i=0;$i<strlen($text);$i++) {
$ord=ord($text[$i]);
if($ord>=192&&$ord<=239) $cout.=chr($ord-64);
elseif($ord>=240&&$ord<=255) $cout.=chr($ord-16);
elseif($ord==168) $cout.=chr(240);
elseif($ord==184) $cout.=chr(241);
elseif($ord==185) $cout.=chr(252);
elseif($ord==150||$ord==151) $cout.=chr(45);
elseif($ord==147||$ord==148||$ord==171||$ord==187) $cout.=chr(34);
elseif($ord>=128&&$ord<=190) $i=$i; //нет представления данному символу
else $cout.=chr($ord);
}