Highlight (Search) Key Words in a Text | PHP
Posted on August 30, 2008, Filled under PHP,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
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.
- 8 comments
Sponsors
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 5 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 4 comments
-
How to Replace and Modify Content Between Two Delimiters in PHPat August 8, 2009 with 1 comment

8 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.