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