15 四月, 2005
判断字符串是否是UTF8编码
为了能够使用“http://www.utblog.com/plog/你的用户名”表示一个UTBlog的网址,需要处理非UTF8编码传送url的情形。这样,就必须能够判断传入的用户名的编码是否是UTF8。
本文最后面是这个判断函数utf8_probability的源码,函数返回的是字符串中UTF8编码部分所占的比例。
参考http://blog.csdn.net/skyyoung/archive/2001/10/15/4142.aspx
同时修改了blogaction.class.php,增加了几行处理$userName的代码,首先include中文编码集合类库(作者Hessian),然后判断userName是否是UTF8编码,如果不是,则假定它是GB2312编码,进行GB2312->UTF8的转换。如果是其他的编码方式,譬如从繁体中文网站点击过来的,则此种转换有可能不成功。
/** utf8_probability
* @param rawtextstr string
* @return number from 0 to 100 representing probability
* text in array uses UTF-8 encoding of Unicode
*/
function utf8_probability($rawtextstr) {
$score = 0;
$i = 0;
$rawtextlen = 0;
$goodbytes = 0;
$asciibytes = 0;
$rawtextarray = preg_split("//",$rawtextstr,-1, PREG_SPLIT_NO_EMPTY); //转换成char数组,如果是php5,则可使用str_split
$rawtext = array();
for($i=0;$i
$rawtext[] = ord($rawtextarray[$i]); //ord(char)
// Maybe also use UTF8 Byte Order Mark(BOM): EF BB BF
//BOM,某些utf8文件流的首3个字节,可以表示这个文件的编码方式
// Check to see if characters fit into acceptable ranges
$rawtextlen = strlen($rawtextstr);
for ($i = 0; $i < $rawtextlen; $i++) {
if ($rawtext[$i] < 0x80) { // One byte
$asciibytes++; // Ignore ASCII, can throw off count
} else if (0xC0 <= $rawtext[$i] && $rawtext[$i] <= 0xDF && // Two bytes
$i+1 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF) {
$goodbytes += 2; $i++;
} else if (0xE0 <= $rawtext[$i] && $rawtext[$i] <= 0xEF && // Three bytes
$i+2 < $rawtextlen && 0x80 <= $rawtext[$i+1] && $rawtext[$i+1] <= 0xBF &&
0x80 <= $rawtext[$i+2] && $rawtext[$i+2] <= 0xBF) {
$goodbytes += 3; $i+=2;
}
}
//ascii is sub of utf8
if ($asciibytes == $rawtextlen) { return 100; }
$score = (int)(100 * ($goodbytes/($rawtextlen-$asciibytes)));
// If not above 98, reduce to zero to prevent coincidental matches
if ($score > 98) {
return $score;
} else if ($score > 95 && $goodbytes > 30) {
// Allows for some (few) bad formed sequences
return $score;
} else {
return 0;
}
}
function utf8_probability(&$rawtextstr) {
$score = 0;
$i = 0;
$rawtextlen = 0;
$goodbytes = 0;
$asciibytes = 0;
$rawtextarray = preg_split("//",$rawtextstr,-1, PREG_SPLIT_NO_EMPTY); //转换成char数组,如果是php5,则可使用str_split
$rawtext = array();
//var_dump($rawtextarray);die;
for($i=0;$i
作者 万维网 07 六月 2005, 00:31


