Highlighting Keywords in Search Results with PHP

Highlighting keywords in search results will help user to identify appropriate results easily. In 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 is occurred. If match found we highlight those keywords by using str_ireplace() function to do case insensitive string replace.

View Demo

highlight-php-search-result

HTML Search Form

We have an search input to enter keywords. We search database to check if atleast any one of the entered search keywords are found.

<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 keyword in 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

This PHP code tutorial was published on May 31, 2016.

↑ Back to Top