Highlighting Keywords in Search Results with PHP

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

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 6, 2023
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

2 Comments on "Highlighting Keywords in Search Results with PHP"

Leave a Reply

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

Explore topics
Need PHP help?