Skip to content Skip to sidebar Skip to footer

Highlighting Keywords In Php Search Script

I have a PHP search script that queries a MySQL database and then parses the results through HTML to allow CSS styling. I want the script to highlight all of the keywords in the re

Solution 1:

Simplistically you could adapt the loop here:

$searchvar = trim($_GET['q']);
while ($row=mysql_fetch_assoc($searchResult)){
    $description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
    $results .="<a href='{$row['url']}' class='webresult'>
    <div class='title'>{$row['title']}</div>
    <div class='desc'>{$description}</div>
    <div class='url'>{$row['url']}</div></a>";
}

To make it a little better:

$searchvar = explode(" ", trim($_GET['q'])); //puts each space separated word into the array.      while ($row=mysql_fetch_assoc($searchResult)){
    $description = $row['description'];
    foreach($searchvaras$var) $description = str_replace($var, '<span class="highlight">'.$var."</span>", $description);
    $description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
    $results .="<a href='{$row['url']}' class='webresult'>
    <div class='title'>{$row['title']}</div>
    <div class='desc'>{$description}</div>
    <div class='url'>{$row['url']}</div></a>";
}

The benefit of the second one there is that if a user types in "ipod toudch yellow" you will be searching for "ipod", "toudch" and "yellow" which would negate the type and make the results more general.

You would need to exchange the single:

like'%query%'

with

foreach(explode(" ", trim($_GET['q']) as$searchvar) $where[] = "like '%$searchvar%'";
$wheresql = implode(" OR ", $where);

to get each search "word" to be looked for in the sql or you will have a limited search with a unrelated highlight.

Solution 2:

i also found this solution to highlight each word of the results:

$text = $searchresults;
classhighlight{
  public$output_text;

  function__construct($text, $words)
  {
    $split_words = explode( " " , $words );

    foreach ($split_wordsas$word)
    {
      $text = preg_replace("|($word)|Ui" , "<b>$1</b>" , $text );
    }
  $this->output_text = $text;
  }
}
$highlight = new highlight($searchresults, $keywords);
echo$highlight;

In case that could help,

Regards,

Max

Solution 3:

you can use regex or simply str replace to look for a particular string and add a span around it:

while ($row=mysql_fetch_assoc($searchResult)){
    $str ="<a href='".$row['url']."' class='webresult'>";
    $str .="<div class='title'>".$row['title']."</div>";
    $str .="<div class='desc'>";
    $str .= str_replace($query,"<span class='hightlighted'>".$query."</span>",$row['description']);
    $str .="</div><div class='url'>".$row['url']."</div></a>";
    $result[] = $str;
}

now the css:

span.highlighted {
   background-color: yellow;
}

Post a Comment for "Highlighting Keywords In Php Search Script"