Home  >  Article  >  Backend Development  >  PHP character encoding conversion problem

PHP character encoding conversion problem

WBOY
WBOYOriginal
2016-07-25 08:53:45935browse
  1. $string=mb_convert_encoding($string, character output encoding, original character encoding);
Copy code

For example: the web page uses gbk encoding, the string uses utf-8 encoding, convert the characters to Web page display encoding.

  1. echo mb_convert_encoding("php encoding conversion", "gbk", "utf-8");
Copy code

Summary: It is recommended to use the mb_convert_encoding function, which has no iconv conversion character error problem.

Convert the encoding of the string to UTF-8. If you know the encoding of the original string, you can use the iconv function that everyone is familiar with. But now you don’t know the encoding of the original string. It may be GBK, or it may be UTF-8, so you cannot use this method. It would be great if you could get the string encoding type, or have an encoding conversion function that automatically recognizes the original string encoding. It turns out that the mb_convert_encoding function is the function that can automatically identify the original string encoding. However, during use, it was found that some Chinese characters in GBK were converted into garbled characters.

Later I found the is_utf8 function in the PHP manual, and then combined with the iconv function, the problem was solved.

Encoding conversion function used:

  1. function is_utf8($string) {
  2. return preg_match('%^(?:
  3. [x09x0Ax0Dx20-x7E] # ASCII
  4. | [xC2-xDF][x80-xBF] # non -overlong 2-byte
  5. | xE0[xA0-xBF][x80-xBF] # excluding overlongs
  6. | [xE1-xECxEExEF][x80-xBF]{2} # straight 3-byte
  7. | x80-xBF] # excluding surrogates
  8. | xF4[x80-x8F][x80-xBF]{2} # plane 16
  9. )*$%xs', $string);
  10. } // function is_utf8
Copy code
Statement:
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