Home > Backend Development > PHP Problem > How to implement ucs2 encoding in php

How to implement ucs2 encoding in php

藏色散人
Release: 2023-03-14 16:26:02
Original
2007 people have browsed it

php method to implement ucs2 encoding: 1. Create a PHP sample file; 2. Implement ucs2 encoding through the "function Ucs2Code($str,$encode="UTF-8"){...}" method That’s it.

How to implement ucs2 encoding in php

#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.

How to implement ucs2 encoding in php?

PHP implements UCS2 encoding and decoding when sending text messages from a mobile phone

The code is as follows:

/***
* @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");
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to implement ucs2 encoding in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template