In regular expressions, ^
can be used to match the beginning of the line and $
to match the end of the line. For example, ^ban
will match banana
, but not urban
, while ban$
matches urban
, but not banana
. These are called anchoring operators.
By default, Relevanssi matches either beginning or the end of the word, but not in the middle – ban
will match banana
or urban
, but not abandon
. If you want more control over this in the search, you can add support for the ^
and $
operators in Relevanssi using the relevanssi_fuzzy_query
filter hook.
add_filter( 'relevanssi_fuzzy_query', 'rlv_edge_operators' ); function rlv_edge_operators( $query ) { if ( isset( $_REQUEST['s'] ) && '^' === substr( $_REQUEST['s'], 0, 1 ) ) { return "(relevanssi.term LIKE '#term#%')"; } if ( isset( $_REQUEST['s'] ) && '$' === substr( $_REQUEST['s'], -1 ) ) { return "(relevanssi.term_reverse LIKE CONCAT(REVERSE('#term#'), '%'))"; } return $query; }
This is a very simple version that works best with single-word searches: it always looks at the first and last character of the whole search query. So, if you search for ^ban foo
, it’s the same as searching for ^ban ^foo
and searching for ban ^foo
is the same as searching for ban foo
.
Creating a smarter version that analyzes the search query and offers support for using different operators for individual words in the query is left as an exercise for the reader.