Highlight Keywords in Search Results with PHP and MySQL
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
- include
- index.php
- README.md
- assets
- css
- style.css
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<style type="text/css"> /* highlight css class */ .search-highlight { font-weight: bold; color: blue; } </style> <?php // Highlight Words in Text function highlightKeywords($string, $words) { preg_match_all('~\w+~', $words, $match); if(!$match) return $string; $result = '~\\b(' . implode('|', $match[0]) . ')\\b~'; return preg_replace($result, '<span class="search-highlight">$0</span>', $string); } ?> |
Highlight Keywords using inline css
1 2 3 4 5 6 7 8 9 10 |
<?php // Highlight Words in Text using inline css function highlightKeywords($string, $words) { preg_match_all('~\w+~', $words, $match); if(!$match) return $string; $result = '~\\b(' . implode('|', $match[0]) . ')\\b~'; return preg_replace($result, '<span style="font-weight: bold; color: blue;">$0</span>', $string); } ?> |
Step 1: First, Create Database
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php CREATE TABLE `news` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `title` varchar(255) DEFAULT NULL, `description` text NOT NULL, `created_date` varchar(12) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `news` (`id`, `name`, `title`, `description`, `created_date`) VALUES (1, 'Team TechArise', 'What is Lorem Ipsum?', 'took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', '1553267453'), (2, 'Team TechArise', 'Where does it come from?', 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.</p><p>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.', '1553267472'), (3, 'Team TechArise', 'Why do we use it?', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '1553267490'); ALTER TABLE `news` ADD PRIMARY KEY (`id`); ALTER TABLE `news` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; ?> |
Step 2: Database Configuration (DBConnection.php)
The following code is used to connect the database using PHP and MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php date_default_timezone_set('Asia/Kolkata'); $root = "http://" . $_SERVER['HTTP_HOST']; $currentDir = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']); $root .= $currentDir; $constants['base_url'] = $root; define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'demo_DB'); define('SITE_URL', $constants['base_url']); define('HTTP_BOOTSTRAP_PATH', $constants['base_url'] . 'assets/vendor/'); define('HTTP_CSS_PATH', $constants['base_url'] . 'assets/css/'); class DBConnection { private $_con; function __construct(){ $this->_con = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE); if ($this->_con->connect_error) die('Database error -> ' . $this->_con->connect_error); } // return Connection function returnConnection() { return $this->_con; } } ?> |
Step 3: Create class and handling database
Create a file like Search.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php require_once(dirname(__FILE__)."/DBConnection.php"); class Search { protected $db; private $_searchKeyword; public function setSearchKeyword($searchKeyword) { $this->_searchKeyword = $searchKeyword; } public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // get Blog Info function public function getBlogInfo() { $query = "SELECT name, title, description, created_date FROM news WHERE title LIKE '%".$this->_searchKeyword."%' OR description LIKE '%".$this->_searchKeyword."%'"; $result = $this->db->query($query) or die($this->db->error); //$data = $result->fetch_all(MYSQLI_ASSOC); $data = array(); while ($row = $result->fetch_assoc()) { $data[] = $row; } return $data; } // highlightKeywords public function highlightKeywords($string, $words) { preg_match_all('~\w+~', $words, $match); if(!$match) return $string; $result = '~\\b(' . implode('|', $match[0]) . ')\\b~'; return preg_replace($result, '<span class="search-highlight">$0</span>', $string); } } ?> |
Step 4: Create html file
Create a html file named index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<?php function __autoload($class) { include "include/$class.php"; } $srch = new Search(); if(!empty($_GET['q'])){ $post = $_GET['q']; } else { $post = ''; } $srch->setSearchKeyword($post); $blogInfo = $srch->getBlogInfo(); ?> <?php include('templates/header.php'); ?> <style type="text/css"> .search-highlight { font-weight: bold; color: blue; } </style> <section class="showcase"> <div class="container"> <div class="row padall border-bottom"> <div class="col-lg-12"> <h2>Highlight Keywords in Search Results with PHP and MySQL</h2> </div> </div> <form action="<?php print SITE_URL;?>" method="get" name="login"> <div class="row padall border-bottom"> <div class="col-lg-12"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search..." value="<?php print $post; ?>"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit"><i class="fa fa-search"></i> Search</button> <a href="<?php print SITE_URL;?>" class="btn btn-outline-secondary"><i class="fa fa-refresh"></i> Reset</a> </div> </div> </div> </div> </form> <div class="row padall"> <?php foreach($blogInfo as $element) { $title = $srch->highlightKeywords($element['title'], $post); $description = $srch->highlightKeywords($element['description'], $post); ?> <div class="col-md-12 border-bottom"> <h3><?php print $title; ?></h3> <div class="clearfix"> <p class="author-category float-left text-muted"><i class="fa fa-user"></i> <?php print $element['name'];?></p> <p class="date-comments float-right text-muted"><i class="fa fa-calendar"></i> <?php print date('j M Y @ h:i a', $element['created_date']); ?></p> </div> <p class="intro"><?php print $description;?></p> </div> <?php } ?> </div> </div> </section> <?php include('templates/footer.php'); ?> |