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

Php 在搜索中突出显示多个关键字,php,html,search,arrays,highlight,Php,Html,Search,Arrays,Highlight,我使用此代码突出显示搜索关键字: function highlightWords($string, $word) { $string = str_replace($word, "<span class='highlight'>".$word."</span>", $string); /*** return the highlighted string ***/ return $string; } .... $cQuote

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

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);
函数highlightWords($string,$word)
{
$string=str_replace($word,“$word.”,$string);
/***返回突出显示的字符串***/
返回$string;
}
....
$cQuote=highlightWords(htmlspecialchars($row['cQuotes']),$search\u result);

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

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

不过,在javascript中执行高亮显示可能会更好。jQuery的“contains”选择器可能有助于避免在运行时替换标记元素的问题


假设这些单词是以空格分隔的字符串输入的,您可以使用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>"
}
所以把它放在一起

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);
}
函数highlightWords($string,$term){
$term=preg_replace('/\s+/','',trim($term));
$words=爆炸(“”,$term);
$highlighted=array();
foreach($words作为$word){
$highlighted[]=“.$word”
}
返回str_replace($words,$highlighted,$string);
}

正则表达式就是最好的选择

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

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

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

 return preg_replace($re, '<SPAN style="BACKGROUND-COLOR: #ffff00"><b>$0</b></SPAN>', $text); 
返回preg_replace($re,$0',$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;
}
function高亮显示文本($text,$words)
{
$split_words=分解(“,$words);
foreach($word拆分为$word)
{
$color=“#e5”;
$text=preg_replace(“|($word)| Ui”,
“$1”,$text);
}
返回$text;
}

调用函数

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

我使用以下方法。它首先形成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;
}
function highlightStr($haystack、$needle、$highlightStyle){
if(strlen($highlightStyle)<1 | strlen($haystack)<1 | strlen($needle)<1){
返回$haystack;
}
preg_match_all(“/$needle+/i”,$haystack,$matches);
$matches[0]=数组_unique($matches[0]);
if(is_数组($matches[0])&&count($matches[0])>=1){
foreach($ii=>$match时匹配[0]
$replace[$ii]=“$match”;
$haystack=str_replace($matches[0],$replace,$haystack);
}
返回$haystack;
}
PHP>5.3.0,试试看

/**
*突出显示匹配字符串
*@param string$文本主题
*@param string$words搜索字符串
*@返回字符串突出显示的文本
*/
公共功能突出显示($text,$words){
$highlighted=preg_filter(“/”.preg_quote($words“/”)。/i',“$0',$text);
如果(!空($突出显示)){
$text=$highlighted;
}
返回$text;
}
在搜索中突出显示多个关键字,包括umlauts 我使用了以前编写的正则表达式,并将
\w
替换为
[A-Za-z0-9äöü196ÖÜ]
。如您所见,我添加了umlauts
äöü196;äÜ
。 我还删除了
\b
,因此它将匹配搜索词的任何外观

例子 搜索词:
苏珊普

文本:
阳光洗发水

结果:
Sun闪亮的shampoo


我使用的代码是:
私有函数getSearchTermToBold($text,$words)
{
pregäu matchúu all(“~[A-Za-z0-9äöÄäääÜ]+”,$words,$m);
如果(!$m)
返回$text;
$re='~('.内爆('|',$m[0]))~i';
返回preg_replace($re,$0',$text);
}

我切换到JavaScript以突出显示搜索。问题是,在属性中搜索值(或搜索,例如,
如何区分大小写?如果用户键入“good”,它将只显示“good”而不是“good”。谢谢。最后一个问题:如果用户键入“good”,它将显示所有突出显示关键字“good”的结果。但是,它不会突出显示“good”一词的“good”,尽管它会显示在结果中。@user187291我如何调整它以处理非英语字符并突出显示为1个字符的关键字?但是如何同时突出显示
ma
单词?如何使它独立于utf-8?对于那些对波浪形字符感到好奇的人来说。它只是用作表达式的分隔符,而不是forward slash/.对我来说是完美的解决方案..有一点变化..非常感谢siri我比其他人尝试得更好::d这一个比公认的答案更好,代码很短,效果很好。太好了!您如何允许搜索这两个字母:
e
é
?我如何指定使用UTF-8以便两个字母都是con考虑突出显示?尝试在preg*之前添加
mb\u内部编码('UTF-8');
,并添加
u
修饰符:
preg\u过滤器('/'.preg\u quote($words)。'/iu',…
这个答案比公认的真实答案要好,现在仍然像一个符咒一样工作
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;
}
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;
}
/**
 * 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;
}
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);
}