Skip to Content
PHP highlight matching text
php code / September 25, 2021

The data list’s search function is really beneficial. It aids in swiftly locating relevant records in the database. The search functionality is made more user-friendly by the search word highlighting feature. The highlight keyword makes it easier for the user to find the most relevant entries in the search results.

In the search results, the search phrases are highlighted with a different background colour or text colour in the keywords highlighting feature. In this lesson, we’ll teach you how to use PHP to search a MySQL database and highlight a keyword inside the results.

Words in Text Should Be Highlighted
highlightWords() is a custom function for highlighting words in a document.

To do a regular expression search and add an element to each matched text, use the PHP preg replace() function.
The element has a class attribute that can be used to determine the highlight colour using CSS.
The highlightWords() function takes two parameters: $text – the material to search and replace, and $replace – the content to replace.
$string – The string to look for.

// Highlight words in text
function highlightWords($text, $word){
$text = preg_replace('#'. preg_quote($word) .'#i', '<span class="hlw">\\0</span>', $text);
return $text;

We’ll get the posts data from the database and list it on the web page in the sample code. The records will be filtered based on the search, and the search term will be highlighted in the search results.

Make a database table.

In the MySQL database, we’ll build a posts table with some basic fields for this example. The records that will be searched and highlighted are stored in the posts table.

CREATE TABLE `posts` (
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Configuring the Database (dbConfig.php)

The PHP and MySQL code below is used to connect to the database. According to your database credentials, specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);

Keywords are highlighted in search results.

All of the records are initially retrieved from the database and displayed on the web page. The words in the search list are highlighted based on the search query.

The records can be filtered using an HTML form based on keywords.
When a user searches for records using a keyword, the WHERE clause is combined with the LIKE operator to filter the results.
The highlightWords() function is used to add the highlighting class to the matched words before presenting the search results.
The connected class is used to highlight the string with CSS once the keywords are wrapped with the highlighting element in the search result.

// Include the database config file
require_once 'dbConfig.php';
// If the search form is submitted
$searchKeyword = $whrSQL = '';
$searchKeyword = $_POST['keyword'];
// SQL query to filter records based on the search term
$whrSQL = "WHERE (title LIKE '%".$searchKeyword."%' OR content LIKE '%".$searchKeyword."%')";
// Get matched records from the database
$result = $db->query("SELECT * FROM posts $whrSQL ORDER BY id DESC");
// Highlight words in text
function highlightWords($text, $word){
$text = preg_replace('#'. preg_quote($word) .'#i', '<span class="hlw">\\0</span>', $text);
return $text;
<!-- Search form -->
<form method="post">
<div class="input-group">
<input type="text" name="keyword" value="<?php echo $searchKeyword; ?>" placeholder="Search by keyword..." >
<input type="submit" name="searchSubmit" value="Search">
<!-- Search results -->
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$title = !empty($searchKeyword)?highlightWords($row['title'], $searchKeyword):$row['title'];
$contnet = !empty($searchKeyword)?highlightWords($row['content'], $searchKeyword):$row['content'];
<div class="list-item">
<h4><?php echo $title; ?></h4>
<p><?php echo $contnet; ?></p>
<?php } }else{ ?>
<p>No post(s) found...</p>
<?php } ?>

Without using CSS, you may highlight keywords.

You may highlight words in the text without needing a CSS class by utilising inline CSS. In this situation, highlightWords() will be changed to look like this.

function highlightWords($text, $word){
$text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text);
return $text;

Note :

Both text and HTML information will be highlighted by our highlightWords() method. You can highlight keywords in search results with HTML content using the sample code. This search highlight feature will come in handy for the data management section’s list. Using PHP and MySQL, you can simply improve our highlight search term feature.

PHPCODE © 2024