Highlight Keywords in Search Results with PHP and MySQL

In this tutorial, We will explain to you how to use highlight words from a search with PHP and MySQL. The PHP preg_match_all() function is used to perform a regular expression search and add a element to each matched string. Highlighting keywords in search results will help a user to easily identify the more relevant records in search results. This is a very simple example, you can just copy-paste, and change according to our requirement.
Before started to implement the Highlight Keywords in Search Results with PHP and MySQL, look a files structure:
  • highlight-keywords-in-search-results-with-php-and-mysql
    • include
      • constants.php
      • DBConnection.php
      • Search.php
    • templates
      • header.php
      • footer.php
  • index.php
  • README.md
  • assets
    • css
      • style.css
To match in a case-insensitive manner, add 'i' to the regular expression. $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i';
Highlight Words in Text
Highlight Keywords using inline css
Step 1: First, Create Database
For this tutorial, you need a MySQL database with the following table:
Step 2: Database Configuration (DBConnection.php)
The following code is used to connect the database using PHP and MySQL.
Step 3: Create class and handling database
Create a file like Search.php.
Step 4: Create html file
Create a html file named index.php