I found this bit of code on stackoverflow at Best practices on displaying search results with associated text snippets from actual result
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;