Search functionality is beneficial for the data list. It helps to find the related records rapidly from the database. The search term highlighting feature makes the search functionality user-friendly. Highlight keyword helps the user to identify the more pertinent records of search results quickly.
In the search Highlight keyword feature, search terms are highlighted in search results with different background colours or text colours. In this tutorial, we will explain to you how to search in the MySQL database and highlight keywords in search results with PHP.
Highlight Words in Text
It is a custom function. Therefore, it will help to highlight the words in the text.
- You can use the PHP preg_replace() function to perform a regular expression search and add an element to each matched string.
- A class attribute is attached to the element. So, you can use it to specify the highlight colour with CSS.
- The highlightWords() function accepts two parameters,
$text
– To replace and search.$word
– The string to search.
// Highlight words in text function highlightWords($text, $word){ $text = preg_replace('#'. preg_quote($word) .'#i', '<span class="hlw">\\0</span>', $text); return $text; }
In the sample code script, we will fetch the posts data from the database and listed on the web page. Therefore, the records will be filtered that are based on a search result, and it will highlight the search term in the search results.
Create Database Table
For this instance, we will make a posts table with some necessary fields in the MySQL database. The posts table holds records that can be searched and highlighted.
CREATE TABLE `posts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `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, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (dbConfig.php)
You can use the following code to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "allsweb"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
SEE ALSO: Live Image Upload, Crop and Resize using jQuery and PHP
Highlight Keywords in Search Results
At first, it will fetch all the records from the database and list them on the web page. According to your most searched keyword, the words are highlighted in the search list.
- An HTML form is provided to filter the records based on the keywords.
- When the user search records by the keyword,
- The WHERE clause is used with the LIKE operator to filter the documents by search term.
- Before displaying the search results, You can use the highlightWords() function to add the highlighting class in the matched words.
- Once you wrap the keywords with the highlighting element in the search result, the attached class is used to highlight the string with CSS.
<?php // Include the database config file require_once 'dbConfig.php'; // If the search form is submitted $searchKeyword = $whrSQL = ''; if(isset($_POST['searchSubmit'])){ $searchKeyword = $_POST['keyword']; if(!empty($searchKeyword)){ // 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"> </div> </form>
<!-- Search results --> <?php 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> </div> <?php } }else{ ?> <p>No post(s) found...</p> <?php } ?>
SEE ALSO: Create PDF with Watermark in PHP using Dompdf
Highlight Keywords without CSS
Use inline CSS to highlight the words in the text without using a CSS class. Therefore, it will modify the highlightWords() like the following.
function highlightWords($text, $word){ $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text); return $text; }
Conclusion
Firstly, our HighlightScript () class will work on both text and HTML content. Secondly, using ou sample code, you can easily highlight keywords in search results with HTML content. Thirdly, this search highlight functionality would be beneficial for the data management section list. Also, you can quickly develop our highlighted search keyword functionality using PHP and MySQL.
Also, read our previous blog- Import and Export CSV File using PHP and MySQL