Highlighting Keywords in Search Results with PHP

by Vincy. Last modified on July 6th, 2023.

Highlighting keywords in search results will help users identify relevant results quickly. In a previous tutorial, we have seen advanced search in PHP. In this example, we are highlighting multiple keywords in search results.

We are searching the database title and description to check if the keyword has occurred. If a match is found, we highlight those keywords using the str_ireplace() function to replace the case-insensitive string.

View Demo

HTML Search Form

We have a search input to enter keywords. We search the database to check if at least any one of the entered search keywords is found.

highlight-php-search-result

<form name="frmSearch" method="post" action="">
	<div class="search-box">
		<label class="search-label">Enter Search Keyword:</label>
		<div>
			<input type="text" name="keyword" class="demoInputBox" value="<?php echo $keyword; ?>"	/>
		</div>				
		<div>
			<input type="submit" name="go" class="btnSearch" value="Search">
		</div>
	</div>
</form>	

Searching and Highlighting Matched Keywords

This PHP code is to search keywords in the title or description. If a match is found, we call the highlightKeywords() method to highlight the keyword in a bold font by adding HTML around the keyword. The code is,

<?php
	$conn = mysqli_connect("localhost", "root", "", "blog_samples");	
	$keyword = "";	
	$queryCondition = "";
	if(!empty($_POST["keyword"])) {
		$keyword = $_POST["keyword"];
		$wordsAry = explode(" ", $keyword);
		$wordsCount = count($wordsAry);
		$queryCondition = " WHERE ";
		for($i=0;$i<$wordsCount;$i++) {
			$queryCondition .= "title LIKE '%" . $wordsAry[$i] . "%' OR description LIKE '%" . $wordsAry[$i] . "%'";
			if($i!=$wordsCount-1) {
				$queryCondition .= " OR ";
			}
		}
	}
	$orderby = " ORDER BY id desc"; 
	$sql = "SELECT * FROM links " . $queryCondition;
	$result = mysqli_query($conn,$sql);	
?>
<?php 
	function highlightKeywords($text, $keyword) {
		$wordsAry = explode(" ", $keyword);
		$wordsCount = count($wordsAry);
		
		for($i=0;$i<$wordsCount;$i++) {
			$highlighted_text = "<span style='font-weight:bold;'>$wordsAry[$i]</span>";
			$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
		}

		return $text;
	}
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page