Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php汉字转码 GBK->Unicode(UTF8)编码转换

php汉字转码 GBK->Unicode(UTF8)编码转换

发布时间:2018-03-16   编辑:www.jquerycn.cn
分享一例php汉字转码的代码,实现gbk到utf8编码的转换,有需要的朋友参考下。

如何实现php汉字编码转换,有关php汉字转码的例子。

该类内置了四个函数"htmlHex","htmlDec","escape","u2utf8"
方便用户的使用,同时也可自定义函数进行自己喜欢的操作

qswhGBK.php文件下载:http://file.jbxue.com/code/201401/qswhGBK.zip

例子:
 

复制代码 代码示例:
<?
//php汉字转码 GBK->Unicode(UTF8)
class qswhGBK{
 var $qswhData;
 function qswhGBK($filename="qswhGBK.php"){
  $this->qswhData=file($filename);
 }
 function gb2u($gb,$callback=""){
  /******(qiushuiwuhen 2002-8-15)******/
  $ret="";
  for($i=0;$i<strlen($gb);$i++){
   if(($p=ord(substr($gb,$i,1)))>127){
   
    $q=ord(substr($gb,++$i,1));
    $q=($q-($q>128?65:64))*4;
    $q=substr($this->qswhData[$p-128],$q,4);
   }
   else
    $q=dechex($p);
   if(empty($callback))
    $ret.=$q;
   else {
    $arr=array("htmlHex","htmlDec","escape","u2utf8");
    if(is_integer($callback)){
     if($callback>count($arr))die("Invalid Function");
     $ret.=$this->$arr[$callback-1]($q);
    }else
     $ret.=$callback($q);
   }
  }
  return $ret;
 }
 
 function htmlHex($str){
  return "&#x".$str.";";
 } // 脚本学堂 www.jbxue.com
 
 function htmlDec($str){
  return "&#".hexdec($str).";";
 }
 
 function escape($str){
  return hexdec($str)<256?chr(hexdec($str)):"%u".$str;
 }
 
 function u2utf8($str){
  /******(qiushuiwuhen 2002-8-15)******/
  $sp="!'()*-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~";
  $dec=hexdec($str);
  $bin=decbin($dec);
  $len=strlen($bin);
  $arr=array("c0","e0","f0");
  if($dec>0x7f){
   $ret="";
   for($i=$len,$j=-1;$i>=0;$i-=6,$j++){
    if($i>6)
     $ret="%".dechex(0x80+bindec(substr($bin,$i-6,6))).$ret;
    else
     $ret="%".dechex(hexdec($arr[$j])+bindec(substr($bin,0,6-$i))).$ret;
   }
  }else{
   if(strpos($sp,chr($dec)))
    $ret=chr($dec);
   else
    $ret="%".strtolower($str);
  }
  return $ret;
 }
}

调用例子:
 

复制代码 代码示例:

$words="中文Abc";
function ex($str){return "[".$str."]";}

$qswh=new qswhGBK("qswhGBK.php");//如果文件名是qswhGBK.php,可省参数

echo("<xmp>不带参数:".$qswh->gb2u($words));
echo("/n调用内置函数htmlHex:".$qswh->gb2u($words,1));
echo("/n调用内置函数htmlDec:".$qswh->gb2u($words,2));
echo("/n调用内置函数escape:".$qswh->gb2u($words,3));
echo("/n调用内置函数u2utf8:".$qswh->gb2u($words,4));
echo("/n调用自定义函数:".$qswh->gb2u($words,ex));

效果:
 

不带参数:4E2D6587416263
调用内置函数htmlHex:&#x4E2D;&#x6587;&#x41;&#x62;&#x63;
调用内置函数htmlDec:&#20013;&#25991;&#65;&#98;&#99;
调用内置函数escape:%u4E2D%u6587Abc
调用内置函数u2utf8:%e4%b8%ad%e6%96%87Abc
调用自定义函数:[4E2D][6587][41][62][63]

您可能感兴趣的文章:
php不使用iconv库进行gb2312与utf-8编码转换的函数
详细阐述PHP环境下如何将GBK编码转成UTF-8格式
汉字转换成Unicode编码PHP程序
一文了解py2/py3编码问题
简单明了!utf8和utf8mb4的区别
php中把unicode编码转化为中文
php汉字转码 Unicode(UTF8)至GBK编码转换
mysql汉字字段按拼音排序的方法
php汉字转码 GBK->Unicode(UTF8)编码转换
python如何解决中文乱码问题

关键词: php汉字转码  编码转换   
[关闭]