Php string encoding conversion program. We often encounter the conversion of uft-8 characters in gbk or gb2312 encoding, but in the use process conversion often encounter some problems, next I will introduce the use of php built-in string conversion function we often encounter the conversion of uft-8 characters in gbk or gb2312 encoding, but in the process of conversion often encounter some problems, the following describes how to use the string conversion function provided by php to implement character encoding conversion.
A bug in the iconv function. Iconv will encounter an error when converting characters "-" to gb2312
The solution is very simple: add "// IGNORE" after the code to be converted, that is, after the second parameter of the iconv function.
As follows:
Reference content is as follows:
| The code is as follows: |
|
Iconv ("UTF-8", "GB2312 // IGNORE", $ data)
|
Ignore indicates that the conversion error is ignored. without the ignore parameter, all strings after this character cannot be saved.
This iconv () function is built in php5.
Column
| The code is as follows: |
|
Echo $ str = 'Hi, it's coffee sale! '; Echo' '; Echo iconv ('gb2312', 'utf-8', $ str); // Encode the string from GB2312 to UTF-8 Echo' '; Echo iconv_substr ($ str, 1, 1, 'utf-8'); // truncate by number of characters rather than bytes Print_r (iconv_get_encoding (); // Obtain the encoding information of the current page. Echo iconv_strlen ($ str, 'utf-8'); // you can specify the length of the encoded string. // This is also applicable. $ Content = iconv ("UTF-8", "gbk // transcoder", $ content ); ?> |
However, when using the iconv function, you may encounter an error such as notice: iconv () [function. iconv]: detected an illegal character in input string,
The reason is that the encoding range is incorrect. gb2312 is smaller than gbk and less than uft8, so pay attention to it during conversion, however, php also provides a function mb_detect_encoding, which can better solve this problem.
Now I want to write it as a more professional function.
| The code is as follows: |
|
Function phpcharset ($ data, $ ){ If (is_array ($ data )){ Foreach ($ data as $ key => $ val ){ $ Data [$ key] = phpcharset ($ val, $ ); } } Else { $ Encode_array = array ('ascii ', 'utf-8', 'gbk', 'gb2312', 'big5 '); $ Encoded = mb_detect_encoding ($ data, $ encode_array ); $ To = strtoupper ($ ); If ($ encoded! = $ ){ $ Data = mb_convert_encoding ($ data, $ to, $ encoded ); } } Return $ data; } ?> |
Sometimes we do not know the character encoding. in this case, we need to detect the encoding before conversion.
| The code is as follows: |
|
Function asciitog ($ brand) { $ Cha = mb_detect_encoding ($ brand ); If ($ cha = 'utf-8 ') { $ Brand2 = iconv ($ cha, "gb2312", $ brand ); } $ Cha2 = mb_detect_encoding ($ brand2 ); If ($ cha2! = 'Ascii '){ $ Brand = $ brand2; } Return $ brand; }
|
...