我不确定这是否是最好的方法,但我过去设置搜索的方法是在数据库中存储一个“词干”字段,其中包含您尝试搜索但已清理和词干的任何内容。
为了清理我通过这个类传递数据,它所做的只是去除所有特殊字符,以及我不想在搜索中包含的特定单词列表:
<?php
class Cleaner {
var $stopwords = array(" find ", " about ", " me ", " ever ", " each ", " update ", " delete ", " add ", " insert ", " where ", " i ", " a ", " my ");//you need to extend this big time.
var $symbols = array('/','\\','\'','"',',','.','<','>','?',';',':','[',']','{','}','|','=','+','-','_',')','(','*','&','^','%','$','#','@','!','~','`');
function parseString($string) {
$string = ' '.$string.' ';
$string = $this->removeStopwords($string);
$string = $this->removeSymbols($string);
return $string;
}
function removeStopwords($string) {
for ($i = 0; $i < sizeof($this->stopwords); $i++) {
$string = str_replace($this->stopwords[$i],' ',$string);
}
//$string = str_replace(' ',' ',$string);
return trim($string);
}
function removeSymbols($string) {
for ($i = 0; $i < sizeof($this->symbols); $i++) {
$string = str_replace($this->symbols[$i],' ',$string);
}
return trim($string);
}
}
然后我使用an implementation of the porter stemmer algorithm 来阻止单词。
然后,在搜索时,您需要对搜索词进行词干化,并与数据库中清理/词干化的词列表进行比较。像SELECT * FROM search WHERE keyword LIKE '%$stem%' 这样简单的东西可能就足够了。
这意味着,例如,如果您搜索“daring”,它将源于“dar”,因此会产生与“dare”和“dares”相同的结果。
可能没有很好地解释它,但希望这些信息足以让你开始 =)