当前位置:首页 > PHP教程 > php函数 > 列表

php 自定义UTF8和cp1251函数

发布:smiling 来源: PHP粉丝网  添加日期:2013-11-28 15:31:44 浏览: 评论:0 

当你需要从utf8转换一些数据,cp1251(窗- 1251)或cp1251到utf8你必须使用系统功能的iconv。常见的主机服务商不允许使用此功能,下面是一个php自定义UTF8和cp1251的函数:

  1. <?php 
  2. */ 
  3. function cp1251_to_utf8($s){ 
  4.            $c209 = chr(209); $c208 = chr(208); $c129 = chr(129); 
  5.            for($i=0; $i<strlen($s); $i++)    { 
  6.                $c=ord($s[$i]); 
  7.                if ($c>=192 and $c<=239) $t.=$c208.chr($c-48); 
  8.                elseif ($c>239) $t.=$c209.chr($c-112); 
  9.                elseif ($c==184) $t.=$c209.$c209
  10.                elseif ($c==168)    $t.=$c208.$c129
  11.                else $t.=$s[$i]; 
  12.            } 
  13.            return $t
  14.        } 
  15.         function utf8_to_cp1251($s
  16.         { 
  17.             for ($c=0;$c<strlen($s);$c++) 
  18.             { 
  19.                $i=ord($s[$c]); 
  20.                if ($i<=127) $out.=$s[$c]; 
  21.                    if ($byte2){ 
  22.                        $new_c2=($c1&3)*64+($i&63); 
  23.                        $new_c1=($c1>>2)&5; 
  24.                        $new_i=$new_c1*256+$new_c2
  25.                    if ($new_i==1025){ 
  26.                        $out_i=168; 
  27.                    } else { 
  28.                        if ($new_i==1105){ 
  29.                            $out_i=184; 
  30.                        } else { 
  31.                            $out_i=$new_i-848; 
  32.                        } 
  33.                    } 
  34.                    $out.=chr($out_i); 
  35.                    $byte2=false; 
  36.                    } 
  37.                if (($i>>5)==6) { 
  38.                    $c1=$i
  39.                    $byte2=true; 
  40.                } 
  41.             } 
  42.             return $out
  43.         } 
  44. ?> 

Tags: 自定义 UTF8 cp1251

分享到: