简体   繁体   English

在搜索结果中突出显示关键字

[英]Highlighting Keyword in search results

How do I highlight keywords in search result? 如何在搜索结果中突出显示关键字?

Here's an example of my code: 这是我的代码示例:

<?php
$mysql = new mysqli($host,$username,$password,$database);

$keyword = 'racing';
$query = $mysql->query("SELECT * FROM products WHERE title LIKE '%$keyword%' OR description LIKE '%$keyword%'");

while($result = $query->fetch_object())
{
    echo '<p>';
    echo $result->title.'<br />';
    echo substr($result->description,'0','256');
    echo '</p>';
}
?>

In this code, the keyword is racing , so I would like all the racing in the search result highlighted. 在此代码中,关键字为racing ,因此我希望搜索结果中的所有racing突出显示。

Just replace your keyword with a styled <span> containing the keyword. 只需用包含关键字的样式<span>替换关键字即可。

$result->title = preg_replace("/($keyword)/i",'<span class="highlight">$1</span>', $result->title);

With $keyword = "racing" and a text "You know racing? It's awesome.", $result->title will be $keyword = "racing"和文本“您知道赛车吗?太棒了”的情况下, $result->title

You know <span class="highlight">racing</span>? It's awesome.

Then you simply style the highlight class using CSS, something like 然后,您只需使用CSS设置Highlight类的样式,例如

.highlight { background-color: #ffa; }  

..... .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM