note 51863 added to function.preg-replace
| From: | php-general at lists dot php dot net | Date: | Wed, 13 Apr 2005 08:36:57 +0000 |
| Subject: | note 51863 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-87943@lists.php.net to get a copy of this message | ||
If you want to highlight certain words with a different background color in your HTML output, then
this function will do the job. This is very useful when displaying search results etc..
<?PHP
// Function highlights $words in $str with the specified $color
function highlight_words($str, $words, $color = '#FFFF00') {
if(is_array($words)) {
foreach($words as $k => $word) {
$pattern[$k] = "/\b($word)\b/is";
$replace[$k] = '<font
style="background-color:'.$color.';">\\1</font>';
}
}
else {
$pattern = "/\b($words)\b/is";
$replace = '<font
style="background-color:'.$color.';">\\1</font>';
}
return preg_replace($pattern,$replace,$str);
}
?>
Hokus
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51863
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51863&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51863&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51863&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51863&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51863&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51863&report=yes
Search -- http://master.php.net/manage/user-notes.php