PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php怎么实现ucs2编码

藏色散人
藏色散人 原创
2021-12-29 10:37:22 1791浏览

php实现ucs2编码的方法:1、创建一个php示例文件;2、通过“function ucs2code($str,$encode="utf-8"){...}”方法实现ucs2编码即可。

本文操作环境:Windows7系统、PHP7.1版、Dell G3电脑。

php怎么实现ucs2编码?

PHP实现UCS2编码解码 手机发送短信时编码

代码如下:

/***
* @Method Ucs2Code UCS2编码
* @Param $str 输入字符串
* @Param $encod 输入字符串编码类型(UTF-8,GB2312,GBK)
* @Return 返回编码后的字符串
*/
function Ucs2Code($str,$encode="UTF-8"){
$jumpbit=strtoupper($encode)=='GB2312'?2:3;//跳转位数
$strlen=strlen($str);//字符串长度
$pos=0;//位置
$buffer=array();
for($pos=0;$pos<$strlen;){
if(ord(substr($str,$pos,1))>=0xa1){//0xa1(161)汉字编码开始
$tmpChar=substr($str,$pos,$jumpbit);
$pos+=$jumpbit;
}else{
$tmpChar=substr($str,$pos,1);
++$pos;
}
$buffer[]=bin2hex(iconv("UTF-8","UCS-2",$tmpChar));
}
return strtoupper(join("",$buffer));
}
/***
* @Method unUcs2Code UCS2解码
* @Param $str 输入字符串
* @Param $encod 输入字符串编码类型(UTF-8,GB2312,GBK)
* @Return 返回解码后的字符串
*/
function unUcs2Code($str,$encode="UTF-8"){  
$strlen=strlen($str);
$step=4;
$buffer=array();
for($i=0;$i<$strlen;$i+=$step){
$buffer[]=iconv("UCS-2",$encode,pack("H4",substr($str,$i,$step)));  
}
return   join("",$buffer);  
}
echo Ucs2Code("进入围栏");
echo unUcs2Code("8FDB516556F4680F");

推荐学习:《PHP视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。