2011-12-15 78 views
4

因此,假設我在我的網站上搜索「古代帝國的故事」。 我的數據庫正在進行全文搜索,結果出來了。我有這個功能亮點thngyPHP搜索結果突出顯示腳本

function sublinhamos($text, $words) { 

    // explode the phrase in words 
    $wordsArray = explode(' ', $words); 

    // loop all searched words 
    foreach($wordsArray as $word) { 
     //highlight 
     $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count); 
    } 
    //right trows results 
    return $text; 
} 

這不是太糟糕了,但這裏的問題是,因爲SEACH而言是「一個古老帝國的故事」時,str_ireplace發現已經插入SPAN的遇到了「一個「來自搜索詞的單詞,並打破SPAN標籤。

我需要突出顯示突出顯示某個單詞的部分,並且所有單詞最多可包含兩個字符,但除舊的SPAN遭遇問題外,這一切都很好。

有什麼想法嗎?

回答

5

那麼,要開始我不會使用跨度。

<mark></mark> 

是更好的使用元素。它的目的是突出顯示這樣的文字部分。有關更多信息,請參閱this article

此外,您還可以傳遞一個數組str_replace函數,例如:

function sublinhamos($text, $words) { 
    $wordsArray = array(); 
    $markedWords = array(); 
    // explode the phrase in words 
    $wordsArray = explode(' ', $words); 

    foreach ($wordsArray as $k => $word) { 
     $markedWords[$k]='<mark>'.$word.'</mark>'; 
    } 

    $text = str_ireplace($wordsArray, $markedWords, $text); 

    //right trows results 
    return $text; 
} 
+1

可能無法解決問題,因爲用戶也可以搜索「標記」。 – mishu 2011-12-15 10:53:06

1

您可以改爲使用將不會被搜索的臨時字符串替換它(例如{{{和}}})是這樣的:

$text = str_ireplace($word, "{{{".strtoupper($word)."}}}", $text, $count); 

標記所有命中後,你可以做一個簡單的替換臨時字符串到你的span標籤

0

可以使用的preg_replace負向後看,而不是:

$text = preg_replace('/(?<!<sp)(?<!<\/sp)(an)/i', '<span class="highlight">$1</span>', $text); 

第一次看,背後是開始跨度標籤和結束標籤的第二個。可能你可以將它們合併成一個,但不確定。

0

你有沒有試過類似的東西?

$text = preg_replace("|($word)|", "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count);