Highlighting Keywords in Search Results with PHP

by Vincy. Last modified on July 10th, 2022.

Highlighting keywords in search results will help a user to identify appropriate results easily. 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 database title and description to check if the keyword has occurred. If match found we highlight those keywords by using str_ireplace() function to do case insensitive string replace.

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 title or description. If match found we call 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

Leave a Reply

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

↑ Back to Top

Share this page