• Main navigation
登入區塊
帳號:

密碼:

記住我



忘記密碼?

現在註冊!
網站資訊區塊
站務管理者

kiang
 

tokimeki
 

sam0228
 

morris
 

shiang
 

SoltyRain
 

廣告





UTF-8中文轉Big5,缺字者改以&#xxxx;代替
Just popping in
註冊日期:
2006/5/10 9:13
文章: 13
如題
Big5轉UTF-8很容易
但UTF-8轉Big5 碰到Big5沒有的字怎辦
有什麼方法可以做到把超出Big5範圍的字用&#xxxx;表示法來替換嗎
這樣就不用擔心UTF-8轉Big5轉出的字串有缺字了

發表日期:2008/3/30 18:12
應用擴展 工具箱


回覆: UTF-8中文轉Big5,缺字者改以&#x;代替
Just popping in
註冊日期:
2006/5/10 9:13
文章: 13
同事找到了在Unicode補完計劃有一個JavaScript工具
http://unicode.at.on.googlepages.com/u_converter.html
可以找出utf8字串中超出big5範圍的字 用&#xxxx;代替
把它改寫成PHP語法 就可以用在server端

function uni2amp$content ) {
  
$newStr "";
  for ( 
$i 0$i iconv_strlen($content,'UTF-8'); $i++ ) {
    
$char iconv_substr($content,$i,1,'UTF-8');
    
$unicode ordUTF8($char);
    
$unicode b5jpcovt$unicode );
    
$newStr .= ( char_check($unicode) ) ? $char "&#" $unicode ";";
  }
  return 
$newStr;
}

b5jpcovt跟char_check是該工具用來轉換、比較字碼的function
看不懂內容 就把它們改成PHP版就對了
ordUTF8則是在www.php.net/ord找到的 用來取得utf8字元的字碼

這樣處理過後字串仍是utf8 但是超出big5字集的內容已經被換成&#xxxx;了
所以就可以

return iconv('UTF-8''BIG-5'uni2amp($str));

不過這個程式只要一跑 當文字內容很多時
CPU loading就會維持100%非常久 >_< 超可怕
以上 留個記錄 歡迎指正

發表日期:2008/4/1 17:54
應用擴展 工具箱


回覆: UTF-8中文轉Big5,缺字者改以&#xxx;代替
Just popping in
註冊日期:
2006/5/10 9:13
文章: 13
更正
發現可以利用mbstring library
轉換更為正確且效率遠遠較高 程式也簡單很多

mb_substitute_character
("long");
mb_regex_encoding('BIG-5');
echo 
convertUnicodeNotation(mb_convert_encoding($data'BIG-5''UTF-8'));

function 
convertUnicodeNotation($str) {
  if(
mb_ereg('U+([0-9A-F]{4})'$str$regs)!==false) {
    return 
convertUnicodeNotation(str_replace($regs[0], '&#'.intval($regs[1],16).';'$str));
  }
  return 
$str;
}
給有需要的人參考

發表日期:2008/4/9 16:44
應用擴展 工具箱


回覆: UTF-8中文轉Big5,缺字者改以
Quite a regular
註冊日期:
2006/3/22 11:14
文章: 49

mb_convert_encoding
($data'HTML-ENTITIES''UTF-8');


這有類似的功用,只是會把所有中文字全部轉成 &#xxxx; 的格式。

發表日期:2008/4/14 12:29
應用擴展 工具箱


回覆: UTF-8中文轉Big5,缺字者改以&#xxx;代替
Just popping in
註冊日期:
2006/11/4 22:44
文章: 1
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=="")?(mb_convert_encoding(substr($utf8_str,$i,3), 'HTML-ENTITIES', 'UTF-8')):$new_word;
$i++;
} else if($sbit > 223 && $sbit < 240) {
$new_word=iconv("UTF-8","Big5",substr($utf8_str,$i,3));
$big5_str.=($new_word=="")?(mb_convert_encoding(substr($utf8_str,$i,3), 'HTML-ENTITIES', 'UTF-8')):$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=="")?(mb_convert_encoding(substr($utf8_str,$i,3), 'HTML-ENTITIES', 'UTF-8')):$new_word;
$i+=3;
}
}
return $big5_str;
}

發表日期:2009/1/17 19:08
應用擴展 工具箱







[進階搜尋]