I’m using this query in my autocomplete feature:
SELECT description FROM my_table WHERE LIKE "%keyword%"
But this query returns the entire content of the field which is sometimes too long.
Is it possible to limit the number of characters before and after "keyword" ?
2
Answers
I suggest using MySQL’s
REGEXP
operator here. For example, to accept a maximum of 10 characters before and after keyword, you could use:Note that if you intend to match
keyword
as a standalone word, you may want to surround it by word boundaries in the regex pattern:To show for example 5 characters before and after you word you can do it using
RIGHT
,LEFT
andSUBSTRING_INDEX
Check it here : https://dbfiddle.uk/MZcVJgEL