Ad

Selecting X Words From A Text Field In MySQL

- 1 answer

I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?

Ad

Answer

You can do it all in the query using SUBSTRING_INDEX

CONCAT_WS(
' ',
-- 20 words before
TRIM(
    SUBSTRING_INDEX(
        SUBSTRING(field, 1, INSTR(field, 'word') - 1 ),
        ' ',
        -20
    )
),
-- your word
'word',
-- 20 words after
TRIM(
    SUBSTRING_INDEX(
        SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ),
        ' ',
        20
    )
)

)

Ad
source: stackoverflow.com
Ad