utf8轉big5之方法

Home Home
引用 | 編輯 笑笑
2007-05-08 15:42
樓主
推文 x0
最近寫程式會用到 utf8 轉 big5,本來想說用iconv就好了

不過我在使用iconv,將utf8轉big5時就出現一個問題,就是只要遇到utf8轉big5,沒有對應的big5碼的時候就有狀況了,原本以為就那個字沒出現,結果是當對應不到big5碼後它是以後的通通不見了,當然這下子就不妙了。

最後我只好一個字一個字轉,然後遇到沒有對應的碼就用"■"代替,雖然損失了效能,但是卻確保了正確性。

本文參考自 http://203.68.102.46/online_book/content.php?chapter_sn=173 感謝 JENY's

複製程式
  //逐字轉換utf8字串為big5
        function  utf8_2_big5($utf8_str)  {
                $i=0;
                $len  =  strlen($utf8_str);
                $big5_str="";
                for  ($i=0;$i<$len;$i++)  {
                        $sbit  =  ord(substr($utf8_str,$i,1));
                        if  ($sbit  <  128)  {
                                $big5_str.=substr($utf8_str,$i,1);
                        }  else  if($sbit  >  191  &&  $sbit  <  224)  {
                                $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,2));
                                $big5_str.=($new_word=="")?"■":$new_word;
                                $i++;
                        }  else  if($sbit  >  223  &&  $sbit  <  240)  {
                                $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,3));
                                $big5_str.=($new_word=="")?"■":$new_word;
                                $i+=2;
                        }  else  if($sbit  >  239  &&  $sbit  <  248)  {
                                $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,4));
                                $big5_str.=($new_word=="")?"■":$new_word;
                                $i+=3;
                        }
                }
                return  $big5_str;
    }  

因為個人需求,當 utf-8 轉 big5 時,對應不到的字,我想要改用   $len = strlen($utf8_str);
    $big5_str="";
    for ($i=0;$i<$len;$i++) {
        $s =substr($utf8_str,$i,1);
        $s1=substr($utf8_str,$i+1,1);
        $s2=substr($utf8_str,$i+2,1);
        $s3=substr($utf8_str,$i+3,1);
        $sbit=ord($s);
        if ($sbit < 0x80) {
            $big5_str.=$s;
        } else if($sbit >= 0xc0 && $sbit < 0xe0) {
            $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,2));
            $big5_str.=$new_word?$new_word:
                '&#'.(((ord($s) & 0x1f) * 0x40) + (ord($s1) & 0x3f)).''
            $i++;
        } else if($sbit >= 0xe0 && $sbit < 0xf0) {
            $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,3));
            $big5_str.=$new_word?$new_word:
                '&#'.(((ord($s) & 0x0f) * 0x1000) + ((ord($s1) & 0x3f) * 0x40) + (ord($s2) & 0x3f)).''
            $i+=2;
        } else if($sbit >= 0xf0 && $sbit < 0xf8) {
            $new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,4));
            $big5_str.=$new_word?$new_word:
                '&#'.(((ord($s) & 0x07) * 0x40000) + ((ord($s1) & 0x3f) * 0x1000) + ((ord($s2) & 0x3f) * 0x40) + (ord($s3) & 0x3f)).''
            $i+=3;
        }
    }
    return $big5_str;
}
[/code][/sell]

獻花 x0
引用 | 編輯 天空星星
2007-11-15 11:39
1樓
  
謝謝樓主的分享
先收藏起來研究學習用
感謝 表情

獻花 x0