Yong Dolah Yong Dolah - 2 years ago 115
PHP Question

Highlighting Keyword in search results

How do I highlight keywords in search result?

Here's an example of my code:

$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
, so I would like all the
in the search result highlighted.

kba kba
Answer Source

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download