WordPress: Highlight search result exact matches

found this neat code to highlight search terms. My problem with the code is that it does not prioritize exact matches and it highlights words within other words.

So searching for in my hometown would also highlight the tool was invented years ago.

So two questions:

  1. How do I make sure that it only finds exact matches?
  2. How do I let the tool try to find and exact match first, and if not found try to find individual strings?

Thanks a lot!

Here the code:

# Highlight query in search results

function generate_excerpt($text, $query, $length) {

$words = explode(' ', $text);
$total_words = count($words);

if ($total_words  $length) {

    $queryLow = array_map('strtolower', $query);
    $wordsLow = array_map('strtolower', $words); 

    $posFound = False;
    for ($i=0; $i = $total_words; $i++) {

        foreach ($queryLow as $queryItem) {
            $searchquery = /\b$queryItem\b/;
            if (preg_match($searchquery, $wordsLow[$i])) {
                $posFound = $i;
                break;
            }
        }

        if ($posFound) {
            break;
        }
    }

    if ($i  ($length+($length/2))) {
        $i = $i - ($length/2);
    } else {
  $i = 0;
}

}

$cutword = array_splice($words,$i,$length);
$excerpt = implode(' ', $cutword);

$keys = implode('|', $query);
$excerpt = preg_replace('/(' . $keys .')/iu', 'strong class=tx-indexedsearch-redMarkup\0/strong', $excerpt);
$excerptRet = 'p';
if ($i !== 0) {
$excerptRet .= '... ';
}
$excerptRet .= $excerpt . ' .../p';

return $excerptRet;

}

function search_excerpt_highlight() {

# Length in word count
$excerptLength = 50;

$rawtext = wp_strip_all_tags( get_the_content() );
$text = preg_replace('#\[.*\]#','',$rawtext);

# Filter double quotes from query. They will
# work on the results side but won't help with
# text highlighting and displaying.
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$term = get_queried_object();

$query=get_search_query(false);
$query=str_replace('','',$query);
$query=esc_html($query);
$query=preg_replace('#\[.*\]#','',$query);

$query = explode(' ', $term-name );

echo generate_excerpt($text, $query, $excerptLength);

}

Found the code here: https://blog.project-insanity.org/2020/07/27/custom-excerpts-in-wordpress-search-highlighting-query-keywords/

Topic regex functions Wordpress search

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.