I would like to write an SQL query that searches for a keyword in a text field, but only if it is a "whole word match" (e.g. when I search for "rid", it should not match "arid", but it should match "a rid".
I am using MySQL.
Fortunately, performance is not critical in this application, and the database size and string size are both comfortably small, but I would prefer to do it in the SQL than in the PHP driving it.
Found an answer to prevent the classic word boundary
[[::<::]]
clashing with special characters eg .@#$%^&*Replace..
With this..
The latter matches (space, tab, etc) || (comma, bracket etc) || start/end of line. A more 'finished' word boundary match.
Use regexp with word boundaries, but if you want also accent insensitive search, please note that REGEXP is a single-byte operator, so it is Worth nothing to have utf8_general_ci collation, the match will not be accent insensitive.
To have both accent insensitive and whole word match, specify the word written in the same way the (deprecated) PHP function sql_regcase() did.
In fact:
utf8_general_ci allows you to make an equality (WHERE field = value) case and accent insensitive search but it doesn't allow you to specify an entire word match (word boundaries markers not recognized)
LIKE allows you case and accent insensitive search but you have to manually specify all combinations of possible word boundaries charactes (word boundaries markers not recognized)
word boundaries [[:<:]] and [[:>:]] are supported in REGEXP, who is a single byte functions so don't perform accent insensitive search.
The solution is to use REGEXP with word boundaries and the word modified in the way sql_regcase does.
Used on http://www.genovaperte.it
This will handle finding rid where it is preceded or followed by a space, you could extend the approach to take account of .,?! and so on, not elegant but easy.
This is the best answer I've come up myself with so far:
I would have simplified it to:
but [^ ] has a special meaning of "NOT a space", rather than "line-beginning or space".
How does REGEXP compare to multiple LIKE conditions? (Not that performance matters in this app.)
You can use
REGEXP
and the[[:<:]]
and[[:>:]]
word-boundary markers: