Yong Dolah
Yong Dolah

Reputation: 43

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.

Upvotes: 2

Views: 2588

Answers (1)

kba
kba

Reputation: 19466

Just replace your keyword with a styled <span> containing the keyword.

$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

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

Then you simply style the highlight class using CSS, something like

.highlight { background-color: #ffa; }  

.....

Upvotes: 5

Related Questions