开发者

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜