Highlight searched keywords in php

A simple function to highlight the search keyword in the text. It first searches the keywords in the text and applies a css class to it.

You can modify your css class of the searched keywords as per your need.

The Css
  <style type="text/css">
  .light{background-color:#AAE2FF;}
  </style>


The PHP function
  
  
function highlight($text, $string) {
  $words=explode(" ",$string);
    foreach ( $words as $word ){
     $text=str_ireplace($word, '<span class="light">'.
$word.'</span>', $text);
    }
  return $text;
  }
 

Call function like this:

$text="This is the text in which the string the and text is to be searched";
$string="the text";

echo highlight($text,$string);
Highlight searched keywords in php Highlight searched keywords in php Reviewed by Altaf Hussain on 12:49 PM Rating: 5

No comments:

Altaf Web. Powered by Blogger.