如何解决搜索结果中重复的摘录里面的内容

问题描述 投票:1回答:1

我成功地高亮了结果,但我面临的问题是,代码重复了结果。例如,即使我只有一个 "这个随机文本 "的出现,代码也会以一种奇怪的方式在摘录内插入重复的结果。困在这里,请大家帮忙。我附上了一张截图,以帮助理解这个问题。你也可以从我的文本中看到,现在的句子没有意义,因为它没有正确地寻找和截断,所以只有包含匹配关键字的段落出现。enter image description here

function wps_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
php
1个回答
2
投票

假设你想把搜索字符串的所有实例(例如 in the beginning)替换为 <strong class="search-excerpt">in the beginning</strong> 那么你就需要修改你的代码。

$text = preg_replace(
    preg_quote("/$sr/iu"),
    '<strong class="search-excerpt">'.$sr.'</strong>',
    $text
);

我在代码中加入了对 preg_quote() 以确保任何可能在 $sr 是适当的逸出。

© www.soinside.com 2019 - 2024. All rights reserved.