PHP字符串处理之全角转半角

public function sbcToDbc($str,$coding='UTF-8'){
    if($coding!='UTF-8'){
        $str=mb_convert_encoding($str,'UTF-8',$coding);
    }
    $ret='';
    for($i=0;$i<strlen($str);$i++){
        $s1=$str[$i];
        if(($c=ord($s1))&0x80){
            $s2=$str[++$i];
            $s3=$str[++$i];
            $c=(($c&0xF)<<12)|((ord($s2)&0x3F)<<6)|(ord($s3)&0x3F);
            if($c==12288){
                $ret.=' ';
            }elseif($c>65280&&$c<65375&&$c!=65374){
                $c-=65248;
                $ret.=chr($c);
            }else{
                $ret.=$s1.$s2.$s3;
            }
        }else{
            $ret.=$str[$i];
        }
    }
    if($coding!='UTF-8'){
        return mb_convert_encoding($ret,$coding,'UTF-8');
    } else{
        return $ret;
    }
}
Last modification:March 18th, 2019 at 01:15 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment