Extracting a relevant sentence

Say you’ve built a PHP / MySQL FULL-TEXT search functionality, and want to display a relevant sentence for each result, in a way like Google does. I’ve written a function that does just that, and thought I’d share it here.

The function takes a multiple sentence text string as input, and a search string. The text is then broken up into sentences with a minimum specified character length (as to avoid any sentences that merely consist of ‘Mr.’, ‘Hi!’, or ‘What?’ ;) ). The first sentence that matches the search string, will then be returned. If no match is found, simply the first sentence of the text will be returned.

Although it’s not perfect, this function generally does the job quite nicely. Download extract_sentencephp.txt here.

For more information on building your own search functionality, have a look at this MySQL FULLTEXT Searching tutorial, and of course at the official documentation.

Explore posts in the same categories: PHP, Web Development

One Comment on “Extracting a relevant sentence”

  1. Fadi Says:

    Thank you, it’s great!
    Happy new year!


Comment: