Jumat, 22 Maret 2019

Highlight Keywords in Search Results with PHP and MySQL

In this tutorial, We will explain 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 ur 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 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, '$0', $string);
}
?>


Highlight Keywords using inline css

// 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, '$0', $string);
}
?>


Step 1: First, Create Database
For this tutorial, you need a MySQL database with the following table:

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.

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.

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.


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, '$0', $string);
}

}

?>


Step 4: Create html file
Create a html file named index.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();

?>
include('templates/header.php');
?>





Highlight Keywords in Search Results with PHP and MySQL












Reset






$title = $srch->highlightKeywords($element['title'], $post);
$description = $srch->highlightKeywords($element['description'], $post);
?>












include('templates/footer.php');
?>


Demo  [sociallocker] Download[/sociallocker]
Disqus Comments