PHP5中的unicode_encode
Posted in PHP by 巫山霏云 on 07-31-2009.最近写的一个脚本涉及到了unicode的编码,但是PHP6之前的PHP都没有原生的支持,因此只能自己手写了。网上找了很多这个函数,但是版本都一样,无非是抄来抄去的。抄也就罢了,问题是这段代码还有一个比较严重的bug:对于某些汉字来说,这个函数的编码会出问题,比如“不”的编码为%u4E0D,这个函数出来的是%u4ed,原因就在于后面那个的字节的数据为d,导致转换后生成的不完全……其实只要加一个判断条件就OK了
附上完美的unicode_encode函数
/** * @description 返回字符串的unicode编码 * @param string $str * @return string encoding */ function unicode_encode($str) { $str =iconv('UTF-8', 'UCS-2', $str); $len = strlen($str); $newstr = ''; for($i = 0; $i < $len - 1; $i = $i + 2) { $c = $str[$i]; $c2 = $str[$i+1]; if (ord($c) > 0) { //tow byte $s = base_convert(ord($c), 10, 16); if(hexdec($s) > 0xF) $newstr .='%u'.$s; else $newstr .='%u'.'0'.$s; $s = base_convert(ord($c2), 10, 16); if(hexdec($s) > 0xF) $newstr .=$s; else $newstr .='0'.$s; } else { $newstr .= $c2; } } return $newstr; } |
新博客的名字不如以前的威武啊…