天天看點

二進制法 PHP,[轉]PHP中文二進制分詞技術函數(UTF-8編碼)

因mysql不直接支援對中文的全文檢索,基于mysql的資料庫的搜尋功能設計一向都成為了難題。

當然想偷懶,完全可以用like來對付,但你的網站的資料量到了幾百萬的時候……使用KingCMS建站的站長,要麼就休了搜尋功能,要麼就考慮轉向其他CMS類系統。

參考了網上的代碼,但基本都是對GBK碼的編碼,在UTF-8下會出錯,是以在UTF-8下重寫了分詞函數,如下:

function wordSegment($str) {

$search = array(":",")","(",".","。",",","!",";","“","”","‘","’","[","]","、","—"," ","《","》","-","…","【","】");

$str=str_replace($search,' ',$str);

//英文單詞3個以上,中文2詞

preg_match_all ('#([A-Za-z0-9]{3,}|([\xC0-\xFF][\x80-\xBF]+)+)#',$str,$array,PREG_PATTERN_ORDER);

$ss=array();

if (!empty($array[1])) {

foreach ($array[1] as $val) {

//英文單詞

if (preg_match('/\w+/',$val)) {

$ss[]=$val;

}else{//中文字元

preg_match_all('#[\xC0-\xFF][\x80-\xBF]+#',$val,$out,PREG_PATTERN_ORDER);

if (!empty($out[0])) {

$count=count($out[0]);

for ($i = 0 ; $i < $count-1 ; $i++) {

$t=$out[0][$i].$out[0][$i+1];

$t=kc_iconv($t,'GBK','UTF-8');

$ss[]=sprintf("%02d%02d%02d%02d",ord($t{0})-160,ord($t{1})-160,ord($t{2})-160,ord($t{3})-160);

}

}

}

}

}

return empty($ss) ? '' : implode(' ',array_unique($ss));

}

function kc_iconv($s,$out='UTF-8',$in='GBK'){

if($out==$in)

return $s;

if(function_exists('iconv')){

$s=iconv($in,"$out//IGNORE",$s);

}elseif(function_exists('mb_convert_encoding')){

$s=mb_convert_encoding($s,$out,$in);

}

return $s;

}

考慮到UTF-8編碼轉換為區位碼後占去6個字元,是以做了iconv轉換,這樣可以減少兩位字元,盡可能的減少索引檔案的大小。

來源:http://hi.baidu.com/sincs/blog/item/5b9546dab3452dd0b6fd488e.html