relevanssi_highlight_regex

apply_filters( 'relevanssi_highlight_regex', string $regex, string $term )

This filter hook filters the regular expression for adding highlights to the excerpt.

Parameters

$regex
(string) The regular expression.

$term
(string) The search term.

More information

When Relevanssi adds highlights to the excerpts, it uses a regular expression to find the search terms in the excerpt. This filter hook can be used to modify that regular expression.

The default value is /([\W])($term)([\W])/iu: the search term, with a word break (\W) on both sides. This looks for complete words. If partial matching is enabled, the regular expression is changed to /([\W]{$term}|{$term}[\W])/iu – the search term with a word break on either end. With the “Expand highlights” setting enabled, the expression is /([\w]*{$term}[\W]|[\W]{$term}[\w]*)/iu.

One use case for this filter would be to change the highlighting so that inside-word highlights are allowed. You can do that with this function:

add_filter( 'relevanssi_highlight_regex', function( $regex, $term ) {
  return "/($term)/iu"
}, 10, 2 );

relevanssi_highlight_regexIf whole-word matching is enabled, the regular expression needs three capture groups where the term is in the middle one, because this regex is replaced with '\\1' . $start_highlight_token . '\\2' . $end_highlight_token . '\\3'. For partial matching, one capture group for the term itself is enough.