Php 彩色搜索词搜索引擎
我想搜索引擎与喜欢的关键字,我想彩色搜索词。 我的代码是:Php 彩色搜索词搜索引擎,php,mysql,Php,Mysql,我想搜索引擎与喜欢的关键字,我想彩色搜索词。 我的代码是: $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); ec
$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>";
$result1=mysql_query(“从archives1中选择*,其中标题类似“%$search%”| |作者类似“%$search%””)或die(mysql_error());
而($row1=mysql\u fetch\u数组($result1))
{
摘录(第1行);
回声“
档案
节:$节
头衔:$Title
作者:$Author
国家:$国家
页码:$pgno”;
若我想用上面的代码搜索任何单词,那个么它会给出正确的答案,但我希望答案是彩色文本。只有搜索单词应该是彩色的
怎么可能呢?
我不知道。使用preg\u replace将搜索到的文本替换为span并向其中添加类
$text = 'sample text';
$query = 'text';
$text = preg_replace('/('.$query.')/','<span class="highlight">$1</span>',$text);
echo $text;
$text='sample text';
$query='text';
$text=preg_replace(“/(“$query”)/”、“$1”、“$text);
echo$文本;
使用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;
}
$title=str_replace($search,“.$search.”,$title);
btw:不要使用mysql,它已经被弃用了。最好切换到mysqli_或PDO,看看它将在哪里使用?提取($row1)之后
但是搜索颜色区分大小写。如果我搜索”和“它搜索”和“带颜色”。但是如果我搜索”和“然后它给出”和“不带颜色”。在简单的文本搜索中为什么使用正则表达式?如果$query包含括号会发生什么?
$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');