PHP 不用iconv()函数 gbk转到unicode(utf8)

添加时间:10-07-16 所属分类:PHP工具与代码
  转载自http://bbs.blueidea.com/thread-597824-1-1.html

请先下载qswhGBK文件,[url:34009v2u]http://www.blueidea.com/user/qswh/qswhGBK.zip[/url:34009v2u]
备用地址[url:34009v2u]http://www.11jn.com/qswhGBK.zip[/url:34009v2u]
[color=#FF0000]下载后,请解压qswhGBK.rar文件获得qswhGBK.php文件,并与你的PHP程序文件放在同一目录下。[/color]
[code]<?
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.";";
}

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;
}
}[/code]

使用范例
[code]
<?php
$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));
?>[/code]
  • 2

前篇:php 不用iconv()函数 UTF8转GB2312字符串编... 后篇:孕妇最易缺的是碘
发表我的评论


推荐文章   日本的开学第一课竟然给孩子讲了这种东...   老人路口卖山货交警掏钱“包圆” 特地让...   泉水故事|有意思!原来济南的泉水类型是...   被宠坏的中国式子女   35岁之后当妈妈——是什么让她们毅然决...
随机文章   php下通过伪造http头破解防盗链的代码   错误syntax error, unexpected T_ENCAP...   php模拟post提交数据,可用来网站的采集...   php防止form重复提交的方法   php中get、request和post的使用
广告

其他推荐

因为本站所有内容均转载自其它媒体,本意为公众提供免费服务,但并不代表本网赞同其观点,也不能对其真实性验证负责,如稿件版权单位或个人不想在本网发布,请与我联系,本人会立即将其撤除,谢谢.联系方式:atseashawk@163.com QQ:99289555