Fonctions iconv

Voir aussi

Voir aussi les GNU Recode.

Sommaire

add a note

User Contributed Notes 2 notes

up
2
Martin Petrov
14 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;
}
}
?>
up
-3
nod at mobi dot kz
17 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);
}
To Top