PHP does not use the iconv library to perform gb2312 and utf-8 encoding conversion functions

WBOY
Release: 2016-07-25 09:08:06
Original
980 people have browsed it
  1. //Usage of comparison table

  2. $filename = "gb2utf8.txt";
  3. $fp = fopen($filename,"r");
  4. while(! feof ($fp)) {
  5. list($gb,$utf8) = fgetcsv($fp,10);
  6. $charset[$gb] = $utf8;
  7. }
  8. fclose($fp);
  9. //The above reading Lookup table to array for later use

  10. /**gb2312 to utf-8**/

  11. function gb2utf8($text, &$charset) {
  12. //Extract the components in the text, Chinese characters are one element, continuous The non-Chinese characters are an element
  13. preg_match_all("/(?:[x80-xff].)|[x01-x7f]+/",$text,$tmp);
  14. $tmp = $tmp[0];
  15. / /Separate Chinese characters
  16. $ar = array_intersect($tmp, array_keys($charset));
  17. //Replace Chinese character encoding
  18. foreach($ar as $k=>$v)
  19. $tmp[$k] = $charset [$v];
  20. //Return the escaped string
  21. return join('',$tmp);
  22. }

  23. /**utf-8 to gb2312**/

  24. function utf82gb($ text, &$charset) {
  25. $p = "/[xf0-xf7][x80-xbf]{3}|[xe0-xef][x80-xbf]{2}|[xc2-xdf][x80-xbf ]|[x01-x7f]+/";
  26. preg_match_all($p,$text,$r);
  27. $utf8 = array_flip($charset);
  28. foreach($r[0] as $k=>$v )
  29. if(isset($utf8[$v]))
  30. $r[0][$k] = $utf8[$v];
  31. return join('',$r[0]);
  32. }< /p>
  33. //Test

  34. $s = gb2utf8('This is a test of the comparison table', $charset);
  35. echo utf82gb($s, $charset);
  36. ?>

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