Highlight multiple Key Words in a Text using php preg_replace

This is quick tutorial to Highlight multiple Key Words in a Text using php preg_replace. If you have created a search feature in your web based project then it is good idea to display Highlighted search Key Words in result to make result more visibile for user.



When user searching text for a specific keyword or keywords, it give the user the option of deciding whether they’d like those keywords highlighted in search results. The following PHP function will highlight defined keywords in text by regular expression.
highlighting-text-php

PHP function to Highlight key words in text

function highlightText($text, $keyword) {
   $color = "red";
   $background = "yellow";
   $keyword = explode(" ", trim($keyword));
   foreach($keyword as $word) {
    $highlightWord =  "<i style='background:".$background.";color:".$color."'>" . $word . "</i>";
	$text = preg_replace ("/" . trim($word) . "/", $highlightWord, $text);
  }
  return $text;
}

For case senstive you have to make little change in preg_replace function add i to apply case senstive.

preg_replace ("/" . trim($word) . "/i", $highlightWord, $text);



Case senstive PHP function to Highlight key words in text

function highlightText($text, $keyword) {
   $color = "red";
   $background = "yellow";
   $keyword = explode(" ", trim($keyword));
   foreach($keyword as $word) {
    $highlightWord =  "<i style='background:".$background.";color:".$color."'>" . $word . "</i>";
	$text = preg_replace ("/" . trim($word) . "/i", $highlightWord, $text);
  }
  return $text;
}

Here is the example..

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s";
$keyword = "Lorem Ipsum text";
echo highlightText($text, $keyword);

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Posted in: PHP

2 Replies to “Highlight multiple Key Words in a Text using php preg_replace”

  1. Hello Rohit,

    Really very good tutorial … I have made some changes in your code to work around case sensitive words. Please have a look and let me know for any concern.


    function highlightText($text, $keyword) {
    $color = "red";
    $background = "yellow";
    //$keyword = explode(" ", trim($keyword));
    foreach($keyword as $word) {
    $text = preg_replace ("/" . trim($word) . "/i", "$0", $text);
    }
    return $text;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.