不用iconv庫(kù)的gb2312與utf-8的互換函數(shù)
更新時(shí)間:2006年10月09日 00:00:00 作者:
一份gb2312.txt(184799字節(jié))確實(shí)顯得太大了點(diǎn),而且還要經(jīng)unicode轉(zhuǎn)換。
這份對(duì)照表為51965字節(jié),要小的多了。
對(duì)于無(wú)法使用iconv函數(shù)庫(kù)的場(chǎng)合還是很實(shí)用的。
<?php
//對(duì)照表的使用
$filename = "gb2utf8.txt";
$fp = fopen($filename,"r");
while(! feof($fp)) {
list($gb,$utf8) = fgetcsv($fp,10);
$charset[$gb] = $utf8;
}
fclose($fp);
//以上讀取對(duì)照表到數(shù)組備用
/** gb2312到utf-8 **/
function gb2utf8($text, &$charset) {
//提取文本中的成分,漢字為一個(gè)元素,連續(xù)的非漢字為一個(gè)元素
preg_match_all("/(?:[\x80-\xff].)|[\x01-\x7f]+/",$text,$tmp);
$tmp = $tmp[0];
//分離出漢字
$ar = array_intersect($tmp, array_keys($charset));
//替換漢字編碼
foreach($ar as $k=>$v)
$tmp[$k] = $charset[$v];
//返回?fù)Q碼后的串
return join('',$tmp);
}
/** utf-8到gb2312 **/
function utf82gb($text, &$charset) {
$p = "/[xf0-xf7][x80-xbf]{3}|[xe0-xef][x80-xbf]{2}|[xc2-xdf][x80-xbf]|[x01-x7f]+/";
preg_match_all($p,$text,$r);
$utf8 = array_flip($charset);
foreach($r[0] as $k=>$v)
if(isset($utf8[$v]))
$r[0][$k] = $utf8[$v];
return join('',$r[0]);
}
//測(cè)試
$s = gb2utf8('這是對(duì)照表的測(cè)試', $charset);
echo utf82gb($s, $charset);
?>
您可能感興趣的文章:
- linux iconv方法的使用
- linux系統(tǒng)上支持php的 iconv()函數(shù)的方法
- PHP通過(guò)iconv將字符串從GBK轉(zhuǎn)換為UTF8字符集
- php iconv() : Detected an illegal character in input string
- php下使用iconv需要注意的問(wèn)題
- PHP iconv 解決utf-8和gb2312編碼轉(zhuǎn)換問(wèn)題
- PHP iconv 函數(shù)轉(zhuǎn)gb2312的bug解決方法
- php中iconv函數(shù)使用方法
- php 轉(zhuǎn)換字符串編碼 iconv與mb_convert_encoding的區(qū)別說(shuō)明
- PHP下編碼轉(zhuǎn)換函數(shù)mb_convert_encoding與iconv的使用說(shuō)明
相關(guān)文章
桌面中心(一)創(chuàng)建數(shù)據(jù)庫(kù)
桌面中心(一)創(chuàng)建數(shù)據(jù)庫(kù)...2006-10-10
php與mysql建立連接并執(zhí)行SQL語(yǔ)句的代碼
進(jìn)入2011年的暑假,已經(jīng)要大三了,也該點(diǎn)更深刻的東西了。綜合各方面的因素,決定還是先學(xué)習(xí)學(xué)習(xí)php,等有所掌獲之后在去了解其他方面的東西。2011-07-07
一個(gè)用于mysql的數(shù)據(jù)庫(kù)抽象層函數(shù)庫(kù)
一個(gè)用于mysql的數(shù)據(jù)庫(kù)抽象層函數(shù)庫(kù)...2006-10-10

