2024 年日本 PHP 研討會

iconv 函式

另請參閱

另請參閱 GNU Recode 函式

目錄

新增註記

使用者貢獻的註記 2 則註記

2
Martin Petrov
15 年前
這是編輯過的函式 utf8_to_cp1251 和 cp1251_to_utf8。
變更:檢查目前的字串編碼。

<?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;
}
}
?>
-3
nod at mobi dot kz
18 年前
如果您需要將字串從 Windows-1251 轉換為 866。某些 1251 的字元在 DOS 866 中沒有表示法。例如,長破折號 -- chr(150) 將被轉換為 0,之後 iconv 完成其工作,其他字元將被跳過。問題字元範圍在 win1251 中 (128-159,163,165-167,169,171-174,177-182,187-190)。

使用這個

//$text - 輸入的 Windows-1251 文字
//$cout - 輸出的 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);
}
To Top