Home >Backend Development >PHP Tutorial >PHP function code to determine character set and transcode

PHP function code to determine character set and transcode

WBOY
WBOYOriginal
2016-07-25 08:56:061237browse
  1. function safeEncoding($string,$outEncoding ='UTF-8')
  2. {
  3. $encoding = "UTF-8";
  4. for($i=0;$i {
  5. if(ord($string{$i})<128)
  6. continue;
  7. if((ord($string{$i})&224)==224)
  8. {
  9. //The first byte passed the judgment
  10. $char = $string{++$i};
  11. if((ord($char)&128)==128)
  12. {
  13. //The second byte passed the judgment
  14. $char = $string{++$i};
  15. if((ord($char)&128)==128)
  16. {
  17. $encoding = "UTF-8";
  18. break;
  19. }
  20. }
  21. }
  22. if((ord($string{$i})&192)==192)
  23. {
  24. //The first byte is judged through
  25. $char = $string{++$i};
  26. if((ord( $char)&128)==128)
  27. {
  28. // The second byte is judged through
  29. $encoding = "GB2312";
  30. break;
  31. }
  32. }
  33. }
  34. if(strtoupper($encoding) == strtoupper ($outEncoding))
  35. return $string;
  36. else
  37. return iconv($encoding,$outEncoding,$string);
  38. }
  39. ?>
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