tags:

views:

41

answers:

2

I found this bit of code on stackoverflow at http://stackoverflow.com/questions/1195947/best-practices-on-displaying-search-results-with-associated-text-snippets-from-ac

However it doesn't quite do what i want. It displays the text around a given search term, but there are two problems

1) I want whole words only; 2) It doesn't limit the characters after the search term, only the ones before

Here's the code below. How can I edit it to solve the two problems? Thanks in advance:

$text = 'This is an example text page with content. It could be red, green or blue or some other random color. It dont really matter.';
$keyword = 'red'; 
$size = 15; // size of snippet either side of keyword
$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...'; 
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet); 
echo $snippet; 
A: 

I made a post here: http://stackoverflow.com/questions/1436582/how-to-generate-excerpt-with-most-searched-words-in-php/2159813#2159813

The messiest code that I have ever written might work for you. I really encourage you to factor out much of the repeated code I have in there.

erisco
A: 
$snippet = preg_replace(
    '/^.*?\s(.{0,'.$size.'})(\b'.$keyword.'\b)(.{0,'.$size.'})\s.*?$/',
    '...$1<strong>$2</strong>$3...',
    $text
);

This will produce: ...It could be <strong>red</strong>, green or blue.... It's the \s character classes that limit the 15-characters to occurring after a word break.

amphetamachine
thanks for the elegant solution
Steven