你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / Linux开发
用php实现gb2312和unicode间的编码转换(1)
 

gb2312 和 unicode 间的编码转换

下面的例子是将 gb2312 转换为 "全"这种形式

php4.3.1以后的iconv函数很好用的,只是需要自己写一个uft8到unicode的转换函数
查表(gb2312.txt)也行
<?
$text = "电子书库";
preg_match_all("/[\x80-\xff]?./",$text,$ar);
foreach($ar[0] as $v)
  echo "&#".utf8_unicode(iconv("GB2312","UTF-8",$v)).";";
?>
<?
// utf8 -> unicode
function utf8_unicode($c) {
  switch(strlen($c)) {
    case 1:
      return ord($c);
    case 2:
      $n = (ord($c[0]) & 0x3f) << 6;
      $n += ord($c[1]) & 0x3f;
      return $n;
    case 3:
      $n = (ord($c[0]) & 0x1f) << 12;
      $n += (ord($c[1]) & 0x3f) << 6;
      $n += ord($c[2]) & 0x3f;
      return $n;
    case 4:
      $n = (ord($c[0]) & 0x0f) << 18;
      $n += (ord($c[1]) & 0x3f) << 12;
      $n += (ord($c[2]) & 0x3f) << 6;
      $n += ord($c[3]) & 0x3f;
      return $n;
  }
}
?>


下面的例子是利用php将"&#20840;"这中编码转换为gb2312.
<?php
$str = "TTL&#20840;&#22825;&#20505;&#33258;&#21160;&#32858;&#28966;";
$str = preg_replace("|&#([0-9]{1,5});|", "\".u2utf82gb(\\1).\"", $str);
$str = "\$str=\"$str\";";

eval($str);
echo $str;

function u2utf82gb($c){
    $str="";
    if ($c < 0x80) {
         $str.=$c;
    } else if ($c < 0x800) {
         $str.=chr(0xC0 | $c>>6);
         $str.=chr(0x80 | $c & 0x3F);
    } else if ($c < 0x10000) {
         $str.=chr(0xE0 | $c>>12);
         $str.=chr(0x80 | $c>>6 & 0x3F);
         $str.=chr(0x80 | $c & 0x3F);
    } else if ($c < 0x200000) {
         $str.=chr(0xF0 | $c>>18);
         $str.=chr(0x80 | $c>>12 & 0x3F);
         $str.=chr(0x80 | $c>>6 & 0x3F);
         $str.=chr(0x80 | $c & 0x3F);
    }
    return iconv('UTF-8', 'GB2312', $str);
}
?>

或者是

function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  $ar = $r[0];
print_r($ar);
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u")
      $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
    elseif(substr($v,0,3) == "&#x")
      $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
    elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."<br>";
      $ar[$k] = iconv("UCS-2","GB2312",pack("n",substr($v,2,-1)));
    }
  }
  return join("",$ar);
}

(编辑:aniston)

  推荐精品文章

·2024年12月目录 
·2024年11月目录 
·2024年10月目录 
·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089