2

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.

Costique
  • 23,712
  • 4
  • 76
  • 79
Yong Dolah
  • 43
  • 1
  • 6
  • possible duplicate of [Highlight keywords in a paragraph](http://stackoverflow.com/questions/4081372/highlight-keywords-in-a-paragraph) – Gumbo Jan 23 '12 at 08:52

1 Answers1

5

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; }  

.....

rene
  • 41,474
  • 78
  • 114
  • 152
kba
  • 19,333
  • 5
  • 62
  • 89