Home >Backend Development >PHP Tutorial >PHP automatically recognizes text encoding and converts it

PHP automatically recognizes text encoding and converts it

WBOY
WBOYOriginal
2016-07-25 08:53:45818browse
  1. /**
  2. * @ string text to be converted
  3. * @ encoding target encoding
  4. **/
  5. function detect_encoding($string,$encoding = 'gbk'){
  6. $is_utf8 = preg_match('%^(?:[x09x0ax0dx20-x7e]| [xc2-xdf][x80-xbf]| xe0[xa0-xbf][x80-xbf] | [xe1-xecxeexef][x80-xbf]{2} | xed[x80-x9f][x80-xbf] | xf0[x90-xbf][x80-xbf]{2} | [xf1-xf3][x80-xbf]{3} | xf4[x80-x8f][x80-xbf]{2} )*$%xs', $string);
  7. if($is_utf8 && $encoding == 'utf8'){
  8. return $string;
  9. }elseif($is_utf8){
  10. return mb_convert_encoding($string, $encoding, "utf-8");
  11. }else{
  12. return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5');
  13. }
  14. }
复制代码


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