Text Highlighter
This simple technique for application developers uses php, css, and html to enhance a site’s search function by highlighting words that match the search keyword.
***
First, define a style with a yellow background color. The stylename in the example is “normhigh”.
<style TYPE=”text/css”>
.normhigh {font-family: “trebuchet MS”; font-size: 45px; color: #000000; background-color: yellow;}
</style>
***
A couple of lines of PHP do the rest of the work. The command, preg_replace(), is used as shown below to wrap a style tag around keywords. $post_content contains the text which is being searched. $highlightstring has the keyword which was entered into a field on the search page. When preg_replace() finds a match, it uses back reference $0 to wrap the class definition ”normhigh” around the matched word.
$skey = $highlightstring;
$pattern = ‘/’ . $skey . ‘/i’;
$post_content = preg_replace($pattern, ‘<span class=normhigh>$0′, $post_content);
The links below show the text highlighter at work:
From php.net, the syntax for preg_replace is:
mixed preg_replace ( $pattern , $replacement , $subject [, int $limit [, int &$count ]] )