Highlight (Search) Key Words in a Text | PHP
Posted on August 30, 2008, under PHP,
Bookmark it
Hello,
This function is useful to highlight words from a simple non-html text. For instance, the search results from your site can be highlighted.
<?php
// Credits: http://www.bitrepository.com/
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter
$style = 'highlight';
$style_i = 'highlight_important';
/* Apply Style */
$var = '';
foreach(explode(' ', $keywords) as $keyword)
{
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";
$str = str_ireplace($keyword, $replacement, $str);
}
/* Apply Important Style */
$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);
return $str;
}
Don’t forget to define your style in the same file or in a separate one (recommended)!
.highlight
{
background: #CEDAEB;
}
.highlight_important
{
background: #F8DCB8;
}
Usage Example:
$str = 'The PHP development team would like to announce the immediate availability of a new PHP version. The PDT project provides a PHP Development Tools framework for the Eclipse platform. PHP is especially suited for Web development and can be embedded into HTML. There are many development tools for PHP.'; $keywords = 'PHP development'; // tags from $keywords are automatically stripped $string = hightlight($str, $keywords); echo $string; ?>
As you can see the full string is highlighted with a different color than the words containing it.
Here’s how our example will look like:

IMPORTANT: This function only works for clean text, without any HTML in it (tags, escaping characters).
Your comments and suggestions are welcomed. Feel free to post them!
Good luck!
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- August 30, 2008
- article by Gabriel C.
- 15 comments
Related Posts
-
How to emphasize specific words from a string (text)at September 6, 2008
-
How to Create an Advanced PHP (bad, naughty) Words Filterat October 26, 2008 with 8 comments
-
PHP: Randomize Text Letters while Keeping the Words Readableat October 4, 2008 with 3 comments
-
How to Create a PHP Word Popularity Scriptat November 7, 2008 with 11 comments
-
Shorten a string (text)at September 3, 2008 with 2 comments

15 Replies to "Highlight (Search) Key Words in a Text | PHP"
September 6, 2008 at 4:18 AM
[...] can also check our keywords highlighter if you want to highlight your keywords in your search results. addthis_url = [...]
October 7, 2008 at 6:10 AM
Disadvantages:
* it will break HTML if keywords match tag or attribute name
* it will not find words that use HTML escaping, contain a tag or soft-hyphen.
You should iterate characters in DOM (or at least match and split whole text nodes via DOM).
October 7, 2008 at 6:45 AM
This is a function that only matches simple text. You can see that in my example I haven’t used any HTML tags, attribute name or escaping characters. I’ve used it in a search script that had results with only clean text and I didn’t take into consideration that it may match any HTML tag or attribute. However, your observation is good and I will consider improving this snippet. Indeed, you don’t know if people will use it in simple or HTML text.
October 7, 2008 at 1:30 PM
Wouldn’t this work using str_ireplace instead of regexes? It looks overkill to me. Actually that’s not the only thing in this code that looks overkill…
Also, CSS directly in HTML is bad practice, just put a class attribute (give it as a parameter to the function) and let people define the style in their CSS.
October 7, 2008 at 2:04 PM
It seems that the code didn’t save correctly last time and some things haven’t shown up between double quotes. I noticed that and updated the post. I’m sorry for the inconvenience.
@Loic Hoguin: Yes, it seems like str_ireplace is an alternative in this case. I just forgot about it when I wrote the function.
Being a short PHP snippet I didn’t want to expand it by separating the CSS style in a file. I was thinking that developers already know how to do that and just added the “style” attribute for highlighting the words.
Thanks for your comment. I will consider upgrading this post.
February 26, 2009 at 7:58 PM
Just wondering an easy way to not allow it to match substrings in the $str string…only whole words.
August 3, 2009 at 9:31 AM
This worked GREAT for what I needed. Thanks a lot!
January 28, 2010 at 3:34 PM
Hey, thanks a bunch for this! I wasn’t sure quite how to go about doing this and your example make it very simple to implement.
September 25, 2010 at 7:00 AM
There is a slight issue with this script it overrides the text words. For example if I search for dog and there is the Dog in the text … this script would output highlighted dog (with lower case d as opposed to the original upper case D) you should consider this as a bug and fix it
September 25, 2010 at 7:41 AM
This keeps the format of the origianl str for me:
$char = stripos($str,$keyword);
if($char!==false)
$replacement = “<span class=’”.$style.”‘>”.substr($str,$char,strlen($keyword)).”</span>”;
October 16, 2010 at 2:32 PM
thanks man,
really nice script,
October 29, 2010 at 2:25 PM
I was looking for something like this for a long time..
Thanks @gabriel and @opa. Very nice and useful function!
November 1, 2010 at 4:52 PM
Gr8… I m searching of actually this
October 5, 2011 at 5:57 AM
The real challenge would be to highlight the whole word containing a string.
For example, in a sentence “I like bitrepository a lot” the keyword would be “repository”, but “bitrepository” would be highlithted.
November 18, 2011 at 10:44 PM
I use preg_replace for this, maybe someone might want to use is:
$str = preg_replace(“/($keyword)(?=[^>]*(<|$))/i",$replacement,$str);