我想搜索引擎与LIKE关键字,我想颜色搜索词。我的代码是:
$result1=mysql_query("SELECT * FROM archives1 where title like '%$search%' || author like '%$search%'") or die (mysql_error());
while($row1=mysql_fetch_array($result1))
{
extract($row1);
echo" <table width='456' height='151' style='table-layout:fixed;'>
<tr><td align='center'>Archives</td></tr>
<tr><td height='38'><b>Section:</b></td><td width='334'>$section</td></tr>
<tr><td height='38'><b>Title:</b></td><td width='334'>$title</td></tr>
<tr><td height='38'><b>Author:</b></td><td width='334'>$author</td></tr>
<tr><td height='38'><b>Country:</b></td><td width='334'>$country</td></tr>
<tr><td height='38'><b>Page Number:</b></td><td width='334'>$pgno</td></tr>";
如果我想用上面的代码搜索任何单词,那么它给出了真实的答案,但我想用彩色文本的答案。只有搜索词应该有颜色
这怎么可能?我不知道。
使用preg_replace将搜索到的文本替换为span,并为其添加一个类。
$text = 'sample text';
$query = 'text';
$text = preg_replace('/('.$query.')/','<span class="highlight">$1</span>',$text);
echo $text;
使用highlight类来样式化结果
您可以使用一个简单的函数来突出显示任意文本:
// Replace string and highlight it
function highlight_words($string, $words, $css_class)
{
//convert searched word to array
$words = array($words);
//cycle
foreach ( $words as $word ) {
$string = str_ireplace($word, '<span class="'.$css_class.'">'.$word.'</span>', $string);
}
/*** return the highlighted string ***/
return $string;
}
示例用法:
$string = 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
$words = array('php', 'sql');
$string = highlightWords($string, $words, 'highlight');