Giving a search term a yellow background color
The function below puts a search term $find
in bold. It works just fine. However, I would like to make it so that instead of putting $find
in bold, it gives it a yellow background, as in the CSS property background-color:#FFFF00;
. How could I do this?
Thanks in advance,
John
The function:
function highlight($text, $words) {
preg_match_all('~\w+~', $words, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
return pre开发者_运维问答g_replace($re, '<b>$0</b>', $text);
}
The PHP/HTML:
echo '<td class="sitename1search"><a href="http://www...com>'.highlight($row["title"], $find)).'</a></td>';
The CSS:
.sitename1search { width: 800px;
font-family: Arial, Helvetica, sans-serif;
font-weight: normal;
font-size: 12px;
overflow:hidden !important;
color: #000000;
padding-bottom: 0px;
}
.sitename1search a{ width: 350px;
font-family: Arial, Helvetica, sans-serif;
font-weight: normal;
font-size: 12px;
overflow:hidden !important;
color: #004284;
padding-bottom: 0px;
}
Replace
return preg_replace($re, '<b>$0</b>', $text);
With
return preg_replace($re, '<span style="background-color:#FFFF00;">$0</span>', $text);
Just add the class
attribute in your PHP:
function highlight($text, $words) {
// your php code
return preg_replace($re, '<span class="found-term">$0</span>', $text); // changed line
}
and add this to your CSS file:
.found-term {
background-color:#FFFF00;
font-weight: bold;
}
It's better than style
attributte in PHP - simply because clashing of logic and design is mostly bad idea.
精彩评论