I am successfully highlighting the results but the problem I'm facing is that the code is duplicating the results. For instance, even when I have just one occurrence of "this random text", the code inserts duplicate results inside the excerpt in a strange way. Stuck here, please help. I have attached a screenshot to help understand the issue. You can also see from my text that the sentence now doesn't make sense because it's not finding and truncating properly so that only the paragraph containing the matching keyword appears.
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');