Author Topic: HOWTO: How to convert between utf8 and cp1251 without iconv  (Read 155 times)

0 Members and 1 Guest are viewing this topic.

Offline MrSpecialist

  • Sr. Member
  • *
  • Posts: 342
  • Karma: +1/-0
  • I'm an expert!
    • View Profile
HOWTO: How to convert between utf8 and cp1251 without iconv
« on: September 14, 2008, 07:06:51 AM »
When you need convert some data from utf8 to cp1251(windows-1251) or cp1251 to utf8 you must use system function iconv. Frequently the hosting providers do not allow to use this function. The code provided would give you some idea on how to do this...just thought for sharing.


Code: [Select]
     
function cp1251_to_utf8($s){
           $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;
       }

        function utf8_to_cp1251($s)
        {
            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;
        }

Techronnati | where technology never sleeps

HOWTO: How to convert between utf8 and cp1251 without iconv
« on: September 14, 2008, 07:06:51 AM »

Mountain View

 

Related Topics

  Subject / Started by Replies Last post
1 Replies
154 Views
Last post November 04, 2008, 12:05:28 AM
by Transformer10

Posting Disclaimer: Any individual may post a message in this forum and may do so anonymously. Therefore, the sole author is exclusively and entirely responsible for all opinions in that message. They do not represent the official opinions of Techronnati, its administrators or moderators or the Techronnati Management. Techronnati is merely acting as an impartial conduit for constitutionally protected free speech and is not responsible and will not be held liable for the content of such messages. All images and service logos are trademarks of their respective owners.