简体   繁体   English

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

[英]highlight multiple keywords in search

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? 如何突出显示多个单词?

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

To match in a case-insensitive manner, add 'i' to the regular expression 要以不区分大小写的方式进行匹配,请在正则表达式中添加“ i”

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

NB: for non-enlish letters like "ä" the results may vary depending on the locale. 注意:对于像“ä”这样的非英语字母,结果可能会因地区而异。

PHP > 5.3.0, try preg_filter() 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;
}

Assuming the words are entered as a space seperated string you can just use explode 假设单词输入为空格分隔的字符串,则可以使用explode

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

Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first 尽管如果要确保没有多个空格,则可能需要先从字符串中删除它们

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

You do then have to generate a replacement array 然后,您必须生成一个替换数组

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

Then 然后

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

So putting it togther 所以放在一起

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

here is simple function to highlight only match text. 这是突出显示仅匹配文本的简单功能。

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

call function 通话功能

Highlight multiple keywords in search including umlauts 突出显示搜索中的多个关键字,包括变音符号

I've used the regex written before and replaced \\w with [A-Za-z0-9_äöüÄÖÜ] . 我使用了以前编写的正则表达式,并用[A-Za-z0-9_äöüÄÖÜ]替换了\\w As you see I added the umlauts äöüÄÖÜ . 如您所见,我添加了变音符äöüÄÖÜ I also have removed the \\b so it will match any appearance of the search term. 我还删除了\\b因此它将匹配搜索词的任何外观。

Example

search term: 搜索词:
Su shamp 苏洗

text: 文本:
Sun shiny shampoo 防晒洗发露

result: 结果:
Su n shiny shamp oo ñ闪亮shamp OO


The code I've used: 我使用的代码:

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

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

 return preg_replace($re, '<SPAN style="BACKGROUND-COLOR: #ffff00"><b>$0</b></SPAN>', $text); 

Splits your search query up into words, then highlight each words separately. 将您的搜索查询分解为单词,然后分别突出显示每个单词。

It might work out better to perform the highlighting in javascript though. 不过,用javascript突出显示可能会更好。 jQuery's "contains" selector will probably help avoid problems of replacing markup elements as you go... jQuery的“包含”选择器可能会帮助避免在您进行替换标记元素时出现问题。

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

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. 它首先形成replace数组,然后将str_replace()与数组参数一起使用-避免了递归。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM