[英]PHP Search for keywords
我一直在為網站上的某些類型的帖子構建PHP搜索工具(為此,請接受mySQL是不可能的)。
經過一系列過程,我們獲得了標題和每個帖子的標簽,並將它們存儲在名為$full
的變量中。
搜索項位於名為$terms
的變量中
$full = $title . ' ' . $tago[$result->ID];
兩者都轉換為小寫。
然后,我們想使用$terms
在$full
尋找相似的詞
我試過了
$final = strpos($full,$terms);
它可以工作,但不如我所需要的那樣好。
這是完整的腳本,如果有幫助的話
$proto = $_GET['p'];
$terms = $_GET['s'];
$terms = strtolower($terms);
$terms = str_replace(' ', '', $terms);
$ids = array();
if($proto == 'inline') {
$search = get_posts('post_type=post&post_status=publish');
foreach($search as $result) {
$title = get_the_title($result);
$tags = wp_get_post_tags( $result->ID);
foreach($tags as $tag){ $tago[$result->ID].= $tag->name;}
$full = $title . ' ' . $tago[$result->ID];
$full = strtolower($full);
$final = strpos($full,$terms);
if($final != false){
$ids[] = $result->ID;
}
}
if ($ids[0] == '') {
echo '<div align="center" style="text-align:center; color:#FFF;">No Results Found</div>';
return false; } else {
$args = array( 'post__in' => $ids );
$srs = get_posts($args);
foreach($srs as $sr) {
echo '<a href="'.$sr->post_slug.'"><img src=""/><b>'.$sr->post_title.'</b>'. $tago[$result->ID].'<span>'.date('dS M Y', strtotime($sr->post_date)).'</span></a>';
}
}
}
價值
$ terms可能包含用戶輸入的一些值,例如“ red car”;
$ full包含帖子標題和標簽,因此可以這樣說。 ``紅色的vaxhaul不是很好,車輛,汽車,可怕,丑陋''
因此,在這種情況下應該可以找到。
您可以通過幾種方式實現它,我將嘗試提供一些方法:
STRPOS
這將匹配紅色,然后停止,但也將匹配不完全相同的單詞,例如car也將匹配卡片等。
$words = explode(' ', $terms);
foreach ($words as $word)
{
if (false !== strpos()) {
$ids[] = $result->ID;
}
}
使用數組間隔
//create an array of searched terms
$words = explode(' ', $terms);
//remove non letter numbers
$fullClean = preg_replace('/[^a-z\d\s]/', '', $full);
//Create an array of words
$criteria = explode(' ', $fullClean);
//find if any elements of $words exist in $criteria
if (count(array_intersect($words, $criteria))) {
$ids[] = $result->ID;
}
第三種方法可能是使用正則表達式和preg_quote,但很可能與strpos有相同的問題
希望能有所幫助
真正的搜索引擎執行此操作的方式是建立一個反向索引,即以其最簡單的形式從每個單詞到其中包含該單詞的文檔集以及查找次數的查找表。 (其中文檔只是意味着要搜索的文本)在php中非常簡單:
foreach($documents as $docIndex => $documentText) {
//remove all types of punctuation and other characters here
$documentText = str_replace(array(',','.','?','!'),"",$documentText);
$words = explode(" ",$documentText);
foreach($words as $word) $invertedIndex[$word][$docIndex]++;
}
運行之后,我們建立了倒排索引。 現在在示例中使用它,傳入查詢為“ red car”。 拆分並查找$ invertedIndex ['red']和$ invertedIndex ['car'],每個返回的數組將包含所有帶有這些單詞的文檔以及其中的次數。 要同時獲取兩個文檔,請使用array_intersect在兩個數組的鍵上使用array_merge獲取文檔:
foreach($keywords as $count => $keyword) {
if($count == 0) $validDocs = keys($invertedIndex[$keyword]);
$validDocs = array_intersect(keys($invertedIndex[$keyword]),$validDocs);
}
現在,每個帶有所有關鍵字的文檔的文檔索引都將在$ validDocs中,如果您想按單詞在文本中出現的次數對它們進行排名,那么您在$ invertedIndex中也可以獲得該信息。 這種方法非常快,但是您必須提前構建倒排索引,但是比實際搜索要快得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.