php 在搜索中突出显示多个关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2757556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:35:20  来源:igfitidea点击:

highlight multiple keywords in search

phphtmlsearcharrayshighlight

提问by input

i'm using this code to highlight search keywords:

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

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);

however, this highlights only one keyword. if the user enters more than one keyword, it will narrow down the search but no word is highlighted. how can i highlight more than one word?

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

回答by user187291

regular expressions is the way to go!

正则表达式是要走的路!

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>
    $re = '~\b(' . implode('|', $m[0]) . ')\b~i';
</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);

To match in a case-insensitive manner, add 'i' to the regular expression

要以不区分大小写的方式进行匹配,请在正则表达式中添加“i”

/**
 * 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">
$words = explode(' ', $term);
</span></b>', $text); if (!empty($highlighted)) { $text = $highlighted; } return $text; }

NB: for non-enlish letters like "?" the results may vary depending on the locale.

注意:对于像“?”这样的非英文字母 结果可能因地区而异。

回答by goldsky

PHP > 5.3.0, try preg_filter()

PHP > 5.3.0,试试preg_filter()

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

回答by Yacoby

Assuming the words are entered as a space seperated string you can just use explode

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

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

Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first

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

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

You do then have to generate a replacement array

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

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);
}

Then

然后

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>
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></b></span>" , $text );
    }
    return $text;
}
</b>', $text); }

So putting it togther

所以把它放在一起

 return preg_replace($re, '<SPAN style="BACKGROUND-COLOR: #ffff00"><b>
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;
}
</b></SPAN>', $text);

回答by Heffa Fuzzel

Highlight multiple keywords in search including umlauts

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

I've used the regex written before and replaced \wwith [A-Za-z0-9_??ü??ü]. As you see I added the umlauts ??ü??ü. I also have removed the \bso it will match any appearance of the search term.

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

Example

例子

search term:
Su shamp

搜索词:
Su shamp

text:
Sun shiny shampoo

文字:
阳光闪亮洗发水

result:
Sun shiny shampoo

结果:
ñ闪亮shampOO



The code I've used:

我使用的代码:

##代码##

回答by asi_x

here is simple function to highlight only match text.

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

##代码##

call function

调用函数

回答by Fou

as suggested by user187291, just change following code in order to get text highlighted with yellow background.

按照 user187291 的建议,只需更改以下代码即可使文本以黄色背景突出显示。

##代码##

回答by Rik Heywood

Splits your search query up into words, then highlight each words separately.

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

It might work out better to perform the highlighting in javascript though. jQuery's "contains" selector will probably help avoid problems of replacing markup elements as you go...

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

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

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

回答by RockwoodON

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.

其他解决方案在查找突出显示项时可能不区分大小写,但不保留原始字符串的大小写。因此,搜索“st”会找到“ST”,但将其突出显示为“st”,即搜索词。

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

我使用以下内容。它首先形成替换数组,然后使用带有数组参数的 str_replace() - 这避免了递归。

##代码##