下面的函数将搜索项$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);
}
Run Code Online (Sandbox Code Playgroud)
PHP/HTML:
echo '<td class="sitename1search"><a href="http://www...com>'.highlight($row["title"], $find)).'</a></td>';
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
更换
return preg_replace($re, '<b>$0</b>', $text);
Run Code Online (Sandbox Code Playgroud)
同
return preg_replace($re, '<span style="background-color:#FFFF00;">$0</span>', $text);
Run Code Online (Sandbox Code Playgroud)
只需class在PHP中添加属性:
function highlight($text, $words) {
// your php code
return preg_replace($re, '<span class="found-term">$0</span>', $text); // changed line
}
Run Code Online (Sandbox Code Playgroud)
并将其添加到您的CSS文件:
.found-term {
background-color:#FFFF00;
font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)
这比style在PHP中的归属要好- 仅仅因为逻辑和设计的冲突主要是坏主意.