• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

unicode_to_utf8 in PHP

php 搞代码 4年前 (2022-01-23) 16次浏览 已收录 0个评论

当短信格式为8:UCS2编码的时候,需要把Unicode的十六进制编码转换成UTF8,但是PHP没有内置Unicode的支持,怎么办呢?

/* *
* 把Unicode的十六进制字符串转换成utf8的文本字符串
* @param mixed $str 要转换的字符串,不能为null
* @return utf8的文本字

。本文来源gao!%daima.com搞$代*!码网1

搞代gaodaima码符串
*/
public static function unicode_hex_to_utf8( $str ) {
// 判断长度
if (( strlen ( $str ) % 4 ) != 0 )
throw new exception ( ‘ (strlen($str) % 4 != 0 ‘ );
// 计算byte[]的长度
$len = strlen ( $str ) / 4 ;
$str_result = ” ;
// 循环复制
for ( $i = 0 ; $i < $len ; $i ++ ){
$str_unicode_hex = substr ( $str , $i * 4 , 4 );
$str_result .= self :: unicode_to_utf8( $str_unicode_hex );
}
return $str_result ;
}

private static function unicode_to_utf8( $unicode_hex ) {

$unicode = hexdec ( $unicode_hex );

$utf8 = ” ;

if ( $unicode < 128 ) {
$utf8 = chr ( $unicode );

} elseif ( $unicode < 2048 ) {
$utf8 .= chr ( 192 + ( ( $unicode – ( $unicode % 64 ) ) / 64 ) );
$utf8 .= chr ( 128 + ( $unicode % 64 ) );

} else {

$utf8 .= chr ( 224 + ( ( $unicode – ( $unicode % 4096 ) ) / 4096 ) );
$utf8 .= chr ( 128 + ( ( ( $unicode % 4096 ) – ( $unicode % 64 ) ) /
64 ) );
$utf8 .= chr ( 128 + ( $unicode % 64 ) );

} // if
return $utf8 ;
} // unicode_to_utf8


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:unicode_to_utf8 in PHP

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址