漢字|轉換
php的漢字轉換一直是比較麻煩的事
該類內建了四個函數"htmlHex","htmlDec","escape","u2utf8"
方便使用者的使用,同時也可自訂函數進行自己喜歡的操作
qswhGBK.php 從這裡下載
http://www.blueidea.com/user/qswh/qswhGBK.zip
<?
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;
}
}
使用範例
$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:中文Abc調用內建函數htmlDec:中文Abc調用內建函數escape:%u4E2D%u6587Abc調用內建函數u2utf8:%e4%b8%ad%e6%96%87Abc調用自訂函數:[4E2D][6587][41][62][63]