php - problem with displaying text around a search term
<p>I found this bit of code on stackoverflow at <a href="http://stackoverflow.com/questions/1195947/best-practices-on-displaying-search-results-with-associated-text-snippets-from-ac">http://stackoverflow.com/questions/1195947/best-practices-on-displaying-search-results-with-associated-text-snippets-from-ac</a></p>

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

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

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

<pre><code>$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, '&lt;strong&gt;'.$keyword.'&lt;/strong&gt;', $snippet); 
echo $snippet; 
</code></pre>
