PHP搜索结果突出显示脚本

edu*_*dev 4 php highlight

所以,我想说我在我的网站上搜索"古代帝国的故事".我的数据库正在进行全文搜索,结果出现了.我有这个功能的亮点thngy

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;
}
Run Code Online (Sandbox Code Playgroud)

这不是太糟糕,但这里的问题是因为搜索术语是"古代帝国的故事",当str_ireplace找到已插入的SPAN时,它会遇到搜索词中的"an"字,并打破SPAN标记.

我需要突出显示突出显示单词的一部分,所有单词最多两个字符,但除了旧的SPAN遇到问题外,它都很好.

有什么想法吗?

Nic*_*ick 5

好吧,开始我不会使用跨度.

<mark></mark>
Run Code Online (Sandbox Code Playgroud)

是更好的元素.它的目的是突出显示这样的文本部分.有关更多信息,请参阅此文章.

此外,您可以将数组传递给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;
}
Run Code Online (Sandbox Code Playgroud)