/**
* 将unicode转换成字符
* @param int $unicode
* @return string UTF-8字符
**/
function unicode2Char($unicode){
if($unicode <128) return chr($unicode);
if($unicode <2048) return chr(($unicode >> 6) &#43; 192) .
chr(($unicode & 63) &#43; 128);
if($unicode <65536) return chr(($unicode >> 12) &#43; 224) .
chr((($unicode >> 6) & 63) &#43; 128) .
chr(($unicode & 63) &#43; 128);
if($unicode <2097152) return chr(($unicode >> 18) &#43; 240) .
chr((($unicode >> 12) & 63) &#43; 128) .
chr((($unicode >> 6) & 63) &#43; 128) .
chr(($unicode & 63) &#43; 128);
return false;
}
/**
* 将字符转换成unicode
* &#64;param string $char 必须是UTF-8字符
* &#64;return int
**/
function char2Unicode($char){
switch (strlen($char)){
case 1 : return ord($char);
case 2 : return (ord($char{1}) & 63) |
((ord($char{0}) & 31) <<6);
case 3 : return (ord($char{2}) & 63) |
((ord($char{1}) & 63) <<6) |
((ord($char{0}) & 15) <<12);
case 4 : return (ord($char{3}) & 63) |
((ord($char{2}) & 63) <<6) |
((ord($char{1}) & 63) <<12) |
((ord($char{0}) & 7) <<18);
default :
trigger_error(&#39;Character is not UTF-8!&#39;, E_USER_WARNING);
return false;
}
}
/**
* 全角转半角
* &#64;param string $str
* &#64;return string
**/
function sbc2Dbc($str){
return preg_replace_callback(
// 全角字符
&#39;/[\x{3000}\x{ff01}-\x{ff5f}]/u&#39;,
function ($matches) {
// 编码转换
// 0x3000是空格&#xff0c;特殊处理&#xff0c;其他全角字符编码-0xfee0即可以转为半角
return ($unicode&#61;$this -> char2Unicode($matches[0])) &#61;&#61; 0x3000 ? " " : (($code&#61;$unicode-0xfee0) > 256 ? $this -> unicode2Char($code) : chr($code));
},
$str);
}
/**
* 半角转全角
* &#64;param string $str
* &#64;return string
**/
function dbc2Sbc($str){
return preg_replace_callback(
// 半角字符
&#39;/[\x{0020}\x{0020}-\x{7e}]/u&#39;,
function ($matches) {
// 编码转换
// 0x0020是空格&#xff0c;特殊处理&#xff0c;其他半角字符编码&#43;0xfee0即可以转为全角
return ($unicode&#61; $this -> char2Unicode($matches[0])) &#61;&#61; 0x0020 ? $this -> unicode2Char(0x3000) : (($code&#61;$unicode&#43;0xfee0) > 256 ? $this -> unicode2Char($code) : chr($code));
},
$str);
}
//使用 方法
$str &#61; &#39;&#xff41;&#xff42;&#xff43;&#xff0c;你好&#xff01;&#39;;
$str_q &#61; $this -> sbc2Dbc($str); //全角转半角
$str_b &#61; $this ->dbc2Sbc($str_q); //半角转全角