不用iconv库的gb2312与utf-8的互换函数
Jun 13, 2016 pm 12:46 PM
一份gb2312.txt(184799字节)确实显得太大了点,而且还要经unicode转换。
这份对照表为51965字节,要小的多了。
对于无法使用iconv函数库的场合还是很实用的。
//对照表的使用
$filename = "gb2utf8.txt";
$fp = fopen($filename,"r");
while(! feof($fp)) {
list($gb,$utf8) = fgetcsv($fp,10);
$charset[$gb] = $utf8;
}
fclose($fp);
//以上读取对照表到数组备用
/** gb2312到utf-8 **/
function gb2utf8($text, &$charset) {
//提取文本中的成分,汉字为一个元素,连续的非汉字为一个元素
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];
//返回换码后的串
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]);
}
//测试
$s = gb2utf8('这是对照表的测试', $charset);
echo utf82gb($s, $charset);
?>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Tips for dynamically creating new functions in golang functions

Considerations for parameter order in C++ function naming

How to write efficient and maintainable functions in Java?

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters

Complete collection of excel function formulas

What are the benefits of C++ functions returning reference types?

Advanced usage of reference parameters and pointer parameters in C++ functions

C++ Function Exception Advanced: Customized Error Handling
