| 以下為引用的內容: //fcicq:下面給大家看看這裡php的分詞是怎麼做的. function &DV_ChineseWordSegment($str,$encodingName=’gbk’){ static $objEnc = null; if( $objEnc === null ){ if( !class_exists(’DV_Encoding’) ){ require_once ROOT_PATH.’inc/DV_Encoding.class.php’; } $objEnc =& DV_Encoding::GetEncoding($encodingName); } $strLen = $objEnc->StrLength($str); $returnVal = array(); if( $strLen < = 1 ){ return $str; } $arrStopWords =& DV_GetStopWordList(); //print_r($arrStopWords); //過濾所有HTML標籤 $str = preg_replace('#<[a-zA-Z]+?.*?>#is’, ”, $str); //過濾所有stopword $str = str_replace($arrStopWords[’StrRepl’],’ ‘,$str); $str = preg_replace($arrStopWords[’PregRepl’],’ ‘,$str); //echo “$str:{$str} “; $arr = explode(’ ‘,$str); //fcicq:好了,這下面的才是php分詞關鍵 ************* foreach( $arr as $tmpStr ){ if ( preg_match(”/^[x00-x7f]+$/i”,$tmpStr) === 1 ) { //fcicq:全是E文,沒關係,mysql可以認識的 $returnVal[] = ‘ ‘.$tmpStr; } else{ //fcicq:中英混合… preg_match_all(”/([a-zA-Z]+)/i”, $tmpStr, $matches); if( !empty($matches) ){ //fcicq:英語部分 foreach( $matches[0] as $matche ){ $returnVal[] = $matche; } } //過濾ASCII字元 $tmpStr = preg_replace(”/([x00-x7f]+)/i”, ” , $tmpStr); //fcicq:你看,剩下的不就全是中文了? $strLen = $objEnc->StrLength($tmpStr)-1; for( $i = 0 ; $i < $strLen ; $i++ ){ $returnVal[] = $objEnc->SubString($tmpStr,$i,2) ; //fcicq:注意這裡的substr,不是手冊上的. //fcicq:你仔細看,所有的詞都是分成兩個. //比如”資料庫的應用”,會被分成資料 據庫 庫的 的應 應用… //全文檢索搜尋: 全文 文搜 搜尋 //這分詞自然是不怎麼樣的 //但是,搜尋的時候同樣這麼做. //比如搜尋資料庫,就相當於搜尋了資料 據庫. //這是一種相當傳統的全文檢索搜尋分詞方法. } } } return $returnVal; }//end function DV_ChineseWordSegment //fcicq:這就是傳說中的substr.偶相信許多人寫出來的php代碼都比這個好. function &SubString(&$str,$start,$length=null){ if( !is_numeric($start) ){ return false; } $strLen = strlen($str); if( $strLen < = 0 ){ return false; } if( $start < 0 $length < 0 ){ $mbStrLen = $this->StrLength($str); } else{ $mbStrLen = $strLen; } if( !is_numeric($length) ){ $length = $mbStrLen; } elseif( $length < 0 ){ $length = $mbStrLen + $length - 1; } if( $start < 0 ){ $start = $mbStrLen + $start; } $returnVal = ''; $mbStart = 0; $mbCount = 0; for( $i = 0 ; $i < $strLen ; $i++ ){ if( $mbCount >= $length ){ break; } $currOrd = ord($str{$i}); if( $mbStart >= $start ){ $returnVal .= $str{$i}; if( $currOrd > 0×7f ){ $returnVal .= $str{$i+1}.$str{$i+2}; $i += 2; } $mbCount++; } elseif( $currOrd > 0×7f ){ $i += 2; } $mbStart++; } return $returnVal; }//end function SubString //插入全文檢索搜尋分詞表.一共兩個,一個 topic_ft,一個bbs_ft $arrTopicIndex =& DV_ChineseWordSegment($topic); if( !empty($arrTopicIndex) && is_array($arrTopicIndex) ){ $topicindex = $db->escape_string(implode(’ ‘,$arrTopicIndex)); if( $topicindex !== ” ){ $db->query(”UPD ATE {$dv}topic_ft SET topicindex=’ {$topicindex}’ WHERE topicid=’{$RootID}’”); } else{ $db->query(”DEL ETE FROM {$dv}topic_ft WHERE topicid=’{$RootID}’”); } } } |