php – problem with displaying text around a search term – Education Career Blog

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; 


$snippet = preg_replace(

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.


I made a post here:
How to generate excerpt with most searched words in PHP?

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.

Leave a Comment