search result highlighting in php

searching in an article for a particular group of words and if found, highlighting the search criteria in the result is really cool. we have seen this in google and many other search engines crawling in the internet. doing texthighlighting in php is fun and easy. i going to describe a little about that.

suppose we are going to search for ‘fineagain’. suppose we have defined a style named ’search’ in css which is different from the style used in the article. we will be displaying search criteria in the result in this style.

let us define some variables according to our need.

$body = is the whole article in which we have found our criteria.

$criteria =’fineagain’;

$startingTag = “<span class=’search’>”;

$endingTag = “</span>”;

$highlightedText = $startingTag . $criteria . $endingTag;

the variable $criteria and $hightedText are same but with different style. we whenever we find $criteria, we replace it with $highlightedText. this will show the search criteria differently in the result.

to replace the $criteria with $highlightedText, we use php library function ‘eregi_replace’.

the defination of the function is:

string eregi_replace(string pattern, string replacement, string textBody);

here pattern is the string we are searching for.

replacement is the string we will use in place of pattern.

textBody is the whole article in which we found our search criteria.

so we will call the function is the following way:

$body = eregi_replace($criteria,$highlightedText,$body);

thats all. now $body contains the same article but the search criteria is highlighted.

this article shows only a single word criterion but it can be extended to multiple word criteria. we can also change highlighting dynamically with utilization of a little prudence.

Post a Comment