日期:2013-07-21 浏览次数:20632 次
函数如下:
function highLight($str, $keywords, $color = "red") {
if (empty($keywords)) {
return $str;
}
$keywords = split("[ \t\r\n,]+", $keywords);
$str_begin = "##~~##~";
$str_end = "~##~~##";
foreach($keywords as $val) {
$tvar = preg_quote($val);
$tvar = str_replace('/', '\/', $tvar);
$patterns[] = "/(" . $tvar . ")/";
$replacement[] = $str_begin . urlencode($val) . $str_end;
$tvar = preg_quote(urlencode($val));
$tvar = str_replace('/', '\/', $tvar);
$tmppattern[] = "/(" . $str_begin . $tvar . $str_end . ")/";
$finalrep[] = "<span style='color:" . $color . "'>" . $val . "</span>";
}
$str = preg_replace($patterns, $replacement, $str);
$str = preg_replace($tmppattern, $finalrep, $str);
return $str;
}