检索结果高亮显示关键词的函数
高亮显示|函数|显示|高亮
如:要检索abc,结果显示akjdfdkcdb,如何才能让其中的abc显示为红色。
函数如下:
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[] = "" . $val . "";
}
$str = preg_replace($patterns, $replacement, $str);
$str = preg_replace($tmppattern, $finalrep, $str);
return $str;
}