S16
S16

Reputation: 2995

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.

Upvotes: 2

Views: 1137

Answers (2)

Ross
Ross

Reputation: 46997

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);
}

Upvotes: 2

Halil Özgür
Halil Özgür

Reputation: 15945

You mean search highlighting:

str_replace(
    $searchTerm,  
    '<span class="searchHighlight">'.$searchTerm.'</span>',
    $searchString);

You need to do this on plain text, otherwise you may come accross some complications as mentioned in the A List Apart article Enhance Usability by Highlighting Search Terms;

You may try a Javascript-based approach, but a PHP/HTML-based one would be more acessible.

Upvotes: 0

Related Questions