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!

Get our RSS Feed!

Related Posts

15 Replies to "Highlight (Search) Key Words in a Text | PHP"

  1. [...] can also check our keywords highlighter if you want to highlight your keywords in your search results. addthis_url = [...]

  2. 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).

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

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

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

  6. Just wondering an easy way to not allow it to match substrings in the $str string…only whole words.

  7. This worked GREAT for what I needed. Thanks a lot!

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

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

  10. 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>”;

  11. thanks man,

    really nice script,

  12. I was looking for something like this for a long time..

    Thanks @gabriel and @opa. Very nice and useful function!

  13. Gr8… I m searching of actually this

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

  15. I use preg_replace for this, maybe someone might want to use is:

    $str = preg_replace(“/($keyword)(?=[^>]*(<|$))/i",$replacement,$str);

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)