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 JS Pixels on January 16, 2012 Rating: 5

No comments:

Altaf Web. Powered by Blogger.