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