This article to introduce the PHP anti-Chinese character to Unicode encoding implementation program method, there is a need to understand the friend can enter the reference.
Program
The code is as follows |
Copy Code |
/** * $str Raw string * $encoding encoding of the original string, default GBK * $prefix encoded prefix, default "" * $postfix the encoded suffix, default ";" */ function Unicode_encode ($str, $encoding = ' GBK ', $prefix = ' ", $postfix = '; ') { $str = Iconv ($encoding, ' UCS-2 ', $str); $arrstr = Str_split ($str, 2); $unistr = "; for ($i = 0, $len = count ($arrstr); $i < $len; $i + +) { $dec = Hexdec (Bin2Hex ($arrstr [$i]); $unistr. = $prefix. $dec. $postfix; } return $unistr; } /** * $STR Unicode-encoded string * $encoding encoding of the original string, default GBK * $prefix prefix of encoded string, default "" " * $postfix The suffix of the encoded string, default ";" */ function Unicode_decode ($unistr, $encoding = ' GBK ', $prefix = ' ", $postfix = '; ') { $arruni = Explode ($prefix, $unistr); $unistr = "; for ($i = 1, $len = count ($arruni); $i < $len; $i + +) { if (strlen ($postfix) > 0) { $arruni [$i] = substr ($arruni [$i], 0, strlen ($arruni [$i])-strlen ($postfix)); } $temp = Intval ($arruni [$i]); $unistr. = ($temp < 256)? Chr (0). Chr ($temp): Chr ($temp/256). Chr ($temp% 256); } Return Iconv (' UCS-2 ', $encoding, $UNISTR); } |
Examples of Use:
The code is as follows |
Copy Code |
GBK string Test $str = ' haha '; echo $str. ' ';
$unistr = Unicode_encode ($STR); echo $unistr. ' '; <b> haha </b>
$str 2 = Unicode_decode ($UNISTR); echo $str 2. ' '; haha
UTF-8 string Test $utf 8_str = iconv (' GBK ', ' UTF-8 ', $str); echo $utf 8_str. ' '; ???? Note: UTF shows the garbled characters under GBK! Switchable Browser-coded test
$utf 8_unistr = Unicode_encode ($utf 8_str, ' UTF-8 '); echo $utf 8_unistr. ' '; <b> haha </b>
$utf 8_str2 = Unicode_decode ($utf 8_unistr, ' UTF-8 '); echo $utf 8_str2. ' '; // ????
Other suffixes, prefix tests $prefix _unistr = Unicode_encode ($str, ' GBK ', ' \u ', '); echo $prefix _unistr. ' '; U60u98u62u21704u21704u60u47u98u62
$profix _unistr2 = Unicode_decode ($prefix _unistr, ' GBK ', ' \u ', '); echo $profix _unistr2. ' '; haha |
http://www.bkjia.com/PHPjc/631560.html www.bkjia.com true http://www.bkjia.com/PHPjc/631560.html techarticle This article to introduce the PHP anti-Chinese character to Unicode encoding implementation program method, there is a need to understand the friend can enter the reference. The program code follows the copy code/** * $str The original string ...