PHP突出显示输入搜索关键字

时间:2017-07-11 08:13:01

标签: php mysql search-engine highlight

我想突出显示每个$ searchkey结果。 我尝试了其他解决方案,但它们不适用于搜索引擎。 结果显示在表格中。 我希望突出显示关键字的每个外观。

感谢您的帮助!

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

1 个答案:

答案 0 :(得分:1)

您可以在PHP中使用正则表达式来执行此操作。在此代码中,我使用<strong>标记,您可以根据需要替换它。

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>"; 
}
相关问题