How to Highlight Matched Keyword in Search using PHP

Getting Started

To beautify the view of this tutorial, I've used Bootstrap which is included in the downloadable of this tutorial but if you want, you can download Bootstrap using this link. Note: preg_filter() function is available on PHP >= 5

Creating our Database

Next, we create the database that we are going to filter in this tutorial. I've included a SQL file in the downloadable of this tutorial. All you have to do is import the said file. If you have no idea on how to import, please visit my tutorial How import .sql file to restore MySQL database. You should be able to create a database named mydb.

Creating our Form and Script

Lastly, we create our search form and the script if the form is submitted. Create a new file, name it as index.php and paste the codes below.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>How to Highlight Matched Keyword in Search using PHP</title>
  6. <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
  7. <style type="text/css">
  8. .mt20{
  9. margin-top:20px;
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <div class="container">
  15. <h1 class="text-center mt20">Highlight Matched Keyword in Search</h1>
  16. <div class="row justify-content-center mt20">
  17. <div class="col-sm-6">
  18. <form method="POST">
  19. <div class="input-group input-group-lg">
  20. <input type="text" name="keyword" class="form-control" placeholder="Firstname, Lastname or Nickname" aria-describedby="basic-addon2">
  21. <div class="input-group-append">
  22. <button class="btn btn-outline-secondary" type="submit" name="search">Search</button>
  23. </div>
  24. </div>
  25. </form>
  26. <?php
  27. if(isset($_POST['search'])){
  28. $keyword = $_POST['keyword'];
  29.  
  30. //connection
  31. $conn = new mysqli('localhost', 'root', '', 'mydb');
  32.  
  33. $sql = "SELECT * FROM members WHERE firstname LIKE '%$keyword%' OR lastname LIKE '%$keyword%' OR nickname LIKE '%$keyword%'";
  34. $query = $conn->query($sql);
  35.  
  36. if($query->num_rows > 0){
  37. echo "<h5 class='mt20'>Search results for '<i>".$keyword."</i>'</h5>
  38. <ul>
  39. ";
  40.  
  41. while($row = $query->fetch_assoc()){
  42.  
  43. $fullname = $row['firstname'].' "'.$row['nickname'].'" '.$row['lastname'];
  44. $highlighted = preg_filter('/' . preg_quote($keyword, '/') . '/i', '<b>$0</b>', $fullname);
  45. echo "<li>".$highlighted."</li>";
  46.  
  47. }
  48.  
  49. echo "</ul>";
  50. }
  51. else{
  52. echo "
  53. <h5 class='mt20'>No search results found for '<i>".$keyword."</i>'</h5>
  54. ";
  55. }
  56.  
  57. }
  58. ?>
  59. </div>
  60. </div>
  61. </div>
  62. </body>
  63. </html>
That ends this tutorial. Happy Coding :)

Add new comment