Search code examples
phpsearchsearch-engine

Get search engine-like search body snippet using php


I have my site search engine functioning exactly the way I want, save for one nagging issue: I want to be able to show the kind of search body that all search engines show where they highlight 1 to 3 sentences that contain your search term(s) in my results.

My Googlefoo is not strong on this one, so I'm hoping someone can turn me on to an existing solution.


Solution

  • In case you're not wanting keyword highlighting as battal suggested and are wanting to snip the relevant paragraph/content this is what I'd do:

    $snippets = array();
    foreach ($matches as $i => $match) {
        $pos = strpos($match, $searchTerm);
    
        $buffer = 30; // characters before and after the search term is found
        // start index - 0 or 30 characters before instance of search term
        $start = ($pos - $buffer >= 0) ? $pos - $buffer : 0;
        // end index - 30 characters after instance of search term or the length of the match
        $end = $start + strlen($searchTerm) + $buffer;
        $end = ($end >= strlen($match)) ? strlen($match) : $end;
    
        $snippets[$i] = substr($match, $start, $end);
    }