Free Web Hosting Forum
(#1 (permalink))
Old
emmanuel's Avatar
Senior Member
emmanuel is on a distinguished road
 
Posts: 213
Join Date: Feb 2011
Location: Somewhere In South Africa
Smile How To Highlight Search Text with PHP - 10-11-2011, 07:54 PM

While performing a search, it's ofter very useful to highlight in different colors.

This function is useful to highlight words from a simple non-html text. For instance, the search results from your site can be highlighted.

Code:
<?php
// Credits: http://www.bitrepository.com/
function hightlight($str, $keywords = '')
{
$keywords = preg_replace('/\s\s+/', ' ', strip_tags(trim($keywords))); // filter

$style = 'highlight';
$style_i = 'highlight_important';

/* Apply Style */

$var = '';

foreach(explode(' ', $keywords) as $keyword)
{
$replacement = "<span class='".$style."'>".$keyword."</span>";
$var .= $replacement." ";

$str = str_ireplace($keyword, $replacement, $str);
}

/* Apply Important Style */

$str = str_ireplace(rtrim($var), "<span class='".$style_i."'>".$keywords."</span>", $str);

return $str;
}
Don’t forget to define your style in the same file or in a separate one (recommended)!

Code:
.highlight
{
background: #CEDAEB;
}

.highlight_important
{
background: #F8DCB8;
}
Very easy stuff, Happy Searching
Reply With Quote
Sponsored Links
Reply

Tags
highlight text, search

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off

Forum Jump



Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.5.2
vBulletin Skin developed by: vBStyles.com