8

我正在使用此代码突出显示搜索关键字:

function highlightWords($string, $word)
 {

        $string = str_replace($word, "<span class='highlight'>".$word."</span>", $string);
    /*** return the highlighted string ***/
    return $string;

 }

 ....

  $cQuote =  highlightWords(htmlspecialchars($row['cQuotes']), $search_result);

但是,这只突出显示了一个关键字。如果用户输入了多个关键字,它将缩小搜索范围,但不会突出显示任何单词。如何突出显示多个单词?

4

8 回答 8

27

正则表达式是要走的路!

function highlight($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~';
    return preg_replace($re, '<b>$0</b>', $text);
}

$text = '
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
';

$words = 'ipsum labore';

print highlight($text, $words);

要以不区分大小写的方式进行匹配,请将 'i' 添加到正则表达式

    $re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';

注意:对于像“ä”这样的非英语字母,结果可能会因语言环境而异。

于 2010-05-03T11:14:54.140 回答
17

PHP > 5.3.0,试试preg_filter()

/**
 * Highlighting matching string
 * @param   string  $text           subject
 * @param   string  $words          search string
 * @return  string  highlighted text
 */
public function highlight($text, $words) {
    $highlighted = preg_filter('/' . preg_quote($words, '/') . '/i', '<b><span class="search-highlight">$0</span></b>', $text);
    if (!empty($highlighted)) {
        $text = $highlighted;
    }
    return $text;
}
于 2015-04-24T05:47:52.497 回答
6

假设单词作为空格分隔的字符串输入,您可以使用explode

$words = explode(' ', $term);

虽然如果你想确保没有多个空格,你可能想先从字符串中删除它们

$term = preg_replace('/\s+/', ' ', trim($term));
$words = explode(' ', $term);

然后你必须生成一个替换数组

$highlighted = array();
foreach ( $words as $word ){
    $highlighted[] = "<span class='highlight'>".$word."</span>"
}

然后

str_replace($words, $highlighted, $string);

所以把它放在一起

function highlightWords($string, $term){
    $term = preg_replace('/\s+/', ' ', trim($term));
    $words = explode(' ', $term);

    $highlighted = array();
    foreach ( $words as $word ){
        $highlighted[] = "<span class='highlight'>".$word."</span>"
    }

    return str_replace($words, $highlighted, $string);
}
于 2010-05-03T11:14:01.793 回答
5

在搜索中突出显示多个关键字,包括变音符号

我使用了之前编写的正则表达式并替换\w[A-Za-z0-9_äöüÄÖÜ]. 如您所见,我添加了变音符号äöüÄÖÜ。我也删除了,\b所以它会匹配搜索词的任何外观。

例子

查询词语:
苏香

文字:
阳光闪亮洗发水

结果:
Sun n 闪亮洗发水oo


我使用的代码:

private function getSearchTermToBold($text, $words)
{
    preg_match_all('~[A-Za-z0-9_äöüÄÖÜ]+~', $words, $m);
    if (!$m)
        return $text;
    $re = '~(' . implode('|', $m[0]) . ')~i';
    return preg_replace($re, '<b>$0</b>', $text);
}
于 2016-07-13T08:49:31.833 回答
4

这是仅突出显示匹配文本的简单功能。

function highlighter_text($text, $words)
{
    $split_words = explode( " " , $words );
    foreach($split_words as $word)
    {
        $color = "#e5e5e5";
        $text = preg_replace("|($word)|Ui" ,
            "<span style=\"background:".$color.";\"><b>$1</b></span>" , $text );
    }
    return $text;
}

调用函数

于 2012-08-07T12:25:57.417 回答
1

正如 user187291 所建议的那样,只需更改以下代码即可以黄色背景突出显示文本。

 return preg_replace($re, '<SPAN style="BACKGROUND-COLOR: #ffff00"><b>$0</b></SPAN>', $text); 
于 2012-07-23T04:58:12.663 回答
0

The other solutions may be case-insensitive in finding the highlight terms, but do not preserve their case of the original string. So searching for "st" will find "ST" but highlight it as "st", the search term.

I use the following. It first forms the replace array, and then uses str_replace() with array parameters - which avoids recursion.

function highlightStr($haystack, $needle, $highlightStyle) {

    if (strlen($highlightStyle) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
       return $haystack;
    }

    preg_match_all("/$needle+/i", $haystack, $matches);

    $matches[0] = array_unique($matches[0]);

    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $ii=>$match)
            $replace[$ii]="<span style='$highlightStyle'>$match</span>";

        $haystack = str_replace($matches[0], $replace, $haystack);
    }

    return $haystack;
}
于 2015-01-17T02:03:49.840 回答
0

将您的搜索查询拆分为单词,然后分别突出显示每个单词。

不过,在 javascript 中执行突出显示可能会更好。jQuery 的“包含”选择器可能有助于避免在您进行时替换标记元素的问题......

http://api.jquery.com/contains-selector/

于 2010-05-03T11:13:10.953 回答