用php實現gb2312和unicode間的編碼轉換

gb2312 和 unicode 間的編碼轉換

下面的例子是將 gb2312 轉換為 “全”這種形式

php(做為現在的主流開發語言)4.3.1以後的iconv函數很好用的,隻是需要自己寫一個uft8到unicode的轉換函數
查表(gb2312.txt)也行
<?
$text = “電子書庫”;
preg_match_all(“/[x80-xff]?./”,$text,$ar);
foreach($ar[0] as $v)
  echo “&#”.utf8_unicode(iconv(“GB2312″,”UTF-8″,$v)).”;”;
?>
<?
// utf8 -> unicode
function utf8_unicode($c) {
  switch(strlen($c)) {
    case 1:
      return ord($c);
    case 2:
      $n = (ord($c[0]) & 0x3f) << 6;
      $n += ord($c[1]) & 0x3f;
      return $n;
    case 3:
      $n = (ord($c[0]) & 0x1f) << 12;
      $n += (ord($c[1]) & 0x3f) << 6;
      $n += ord($c[2]) & 0x3f;
      return $n;
    case 4:
      $n = (ord($c[0]) & 0x0f) << 18;
      $n += (ord($c[1]) & 0x3f) << 12;
      $n += (ord($c[2]) & 0x3f) << 6;
      $n += ord($c[3]) & 0x3f;
      return $n;
  }
}
?>

下面的例子是利用php(做為現在的主流開發語言)將”全”這中編碼轉換為gb2312.
<?php(做為現在的主流開發語言)
$str = “TTL全天候自动聚焦”;
$str = preg_replace(“|&#([0-9]{1,5});|”, “”.u2utf82gb(\1).””, $str);
$str = “$str=”$str”;”;

eval($str);
echo $str;

function u2utf82gb($c){
    $str=””;
    if ($c < 0x80) {
         $str.=$c;
    } else if ($c < 0x800) {
         $str.=chr(0xC0 | $c>>6);
         $str.=chr(0x80 | $c & 0x3F);
    } else if ($c < 0x10000) {
         $str.=chr(0xE0 | $c>>12);
         $str.=chr(0x80 | $c>>6 & 0x3F);
         $str.=chr(0x80 | $c & 0x3F);
    } else if ($c < 0x200000) {
         $str.=chr(0xF0 | $c>>18);
         $str.=chr(0x80 | $c>>12 & 0x3F);
         $str.=chr(0x80 | $c>>6 & 0x3F);
         $str.=chr(0x80 | $c & 0x3F);
    }
    return iconv(UTF-8, GB2312, $str);
}
?>

或者是

function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all(“/(?:%u.{4})|&#x.{4};|&#d+;|.+/U”,$str,$r);

You May Also Like