0

I have a PHP search script and I want to highlight the keywords that the user has searched with tags. How can I do this?

My code is:

if(!empty($_GET['q'])){
$keywords=explode(' ',$_GET['q']);
foreach($keywords as $query){
$query=mysql_real_escape_string($query);
$likes[]="keywords LIKE '%{$query}%'";
}

$searchResult=mysql_query("select * from questions where ".implode('or ',$likes)."limit 1");
while($row=mysql_fetch_assoc($searchResult)){
    $results="<div class='webresult'>{$row['result']}</div>";
}
}
Callum Whyte
  • 2,379
  • 11
  • 36
  • 55

2 Answers2

0

If $row['result'] does not contain html, you can do a string replace: replace all keywords in the result with <span class="highlight">keyword</span>

A simple example:

...
while($row=mysql_fetch_assoc($searchResult)) {
  $res = $row['result'];
  foreach($keywords as $kw) {
    $res = str_replace($kw, '<span class="highlight">' . htmlspecialchars($kw) . '</span>', $res);
  }
  $results="<div class='webresult'>{$res}</div>";
}
...
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • @Cosmo Posmo See Blowski's answer, but your search results are not reliable anyway as the visitor can enter for example an html tag as a search term. – jeroen Jan 14 '12 at 16:11
  • @Cosmo Posmo I have added the complete `while` loop for the mysql results. – jeroen Jan 14 '12 at 16:13
  • @Cosmo Posmo Sorry about that, just use `str_ireplace()` instead of `str_replace()` – jeroen Jan 14 '12 at 16:41
0

Two solutions, depending on whether the result can contain HTML or not.

  1. If the result can't contain HTML - use preg_replace. See here: highlight multiple keywords in search

  2. If it can contain HTML, then you will need to use a DOM parser to separate text from HTML. Example parsers include Simple HTML Dom and DOMDocument.

Community
  • 1
  • 1
Dan Blows
  • 20,846
  • 10
  • 65
  • 96