下面的函数将搜索词 $find
加粗。它工作得很好。但是,我想这样做,而不是将 $find
加粗,而是给它一个黄色背景,如 CSS 属性 background-color:#FFFF00;
。我怎么能这样做?
提前致谢
约翰
函数:
function highlight($text, $words) {
preg_match_all('~\w+~', $words, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
return preg_replace($re, '<b>$0</b>', $text);
}
PHP/HTML:
echo '<td class="sitename1search"><a href="http://www...com>'.highlight($row["title"], $find)).'</a></td>';
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;
}
最佳答案
替换
return preg_replace($re, '<b>$0</b>', $text);
与
return preg_replace($re, '<span style="background-color:#FFFF00;">$0</span>', $text);
关于php - 为搜索词提供黄色背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3568929/