Automatically identify text encoding and convert to target encoding!

WBOY
Release: 2016-07-25 09:06:49
Original
963 people have browsed it

When PHP processes pages, we use functions such as iconv or mb_convert to convert character sets, but this actually has a premise. That is, we must know in advance what encoding in and out are so that we can perform the correct conversion.

Although most conversions are between gbk and utf-8, what if you don’t know the encoding of the conversion object? Google has come up with such a function safeEncoding, which can easily identify the encoding of UTF8 and GBK. This function is very accurate to a certain extent, but it is not so easy to use in some more complex environments. Below I combine the differences between GBK and UTF-8 encoding and use regular expressions to determine UTF-8 Encode and use the mb_convert_encoding function to convert. In China, the most popular encodings are GBK and UTF-8, so this function automatically converts these two encodings.

  1. /**
  2. * Source URL: http://www.xuehuwang.com/read-450.html
  3. * Author: Xuehu Blog
  4. * @ string Text to be converted
  5. * @ encoding Target encoding
  6. **/
  7. function detect_encoding($string,$encoding = 'gbk'){
  8. $is_utf8 = preg_match('%^(?:[x09x0Ax0Dx20-x7E]| [xC2-xDF] [x80-xBF]| xE0[xA0-xBF][x80-xBF] | [xE1-xECxEExEF][x80-xBF]{2} | [x80-xBF]{2} | [xF1-xF3][x80-xBF]{3} | xF4[x80-x8F][x80-xBF]{2} )*$%xs', $string);
  9. if ($is_utf8 && $encoding == 'utf8'){
  10. return $string;
  11. }elseif($is_utf8){
  12. return mb_convert_encoding($string, $encoding, "UTF-8");
  13. }else{
  14. return mb_convert_encoding ($string, $encoding, 'gbk,gb2312,big5');
  15. }
  16. }
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!