Search code examples
phpmysqlsearch-enginehighlight

PHP Highlight Input Search Keyword


I want to highlight every $searchkey results. I tried other solutions but they don't work with a search engine. Results appear in a table. I want every appearance of the keyword to be highlighted.

Thanks for your help!

<?php
$dbhost = 'xxx';
$username = 'xxx';
$password = 'xxx';

mysql_connect("$dbhost" , "$username", "$password" );
mysql_select_db("xxx") or die("could not find the database!");
$output = '';


if(isset($_GET['search']))
{
    $searchkey = $_GET['search'];
    $query = mysql_query("SELECT * FROM xxx WHERE email LIKE '%$searchkey%' ") or die("Could not search");
    $count = mysql_num_rows($query);

    if ($count == 0) 
    {
        $output = 'There was no search results !' ;
    }
    else 
    {
    echo '<table class="table table-striped table-bordered table-hover">'; 
    echo "<tr><th>email</th><th>hashkey</th></tr>"; 

        while ($row = mysql_fetch_array($query))
         {

            $email = $row['email'];
            $hashkey = $row['hashkey'];
            echo "<tr><td>"; 
            echo $email;
            echo "</td><td>";   
            echo $hashkey;   
            echo "</td></tr>";  
        }
            echo '<div>'."$count results were found for '$searchkey'.".'</div>'.'</br>';

    }
    echo "</table>";   
    $searchkey= $words;
}
?>

Solution

  • You can use Regular Expression in PHP to do this. In this code I use <strong> tag, you can replace it as you want.

    while ($row = mysql_fetch_array($query))
    {
    
        $email = preg_replace('/(' . $searchkey . ')/s', '<strong>\1</strong>', $row["email"]);
        $hashkey = $row['hashkey'];
        echo "<tr><td>";
        echo $email;
        echo "</td><td>";  
        echo $hashkey;  
        echo "</td></tr>"; 
    }