Highlighting keywords in search results using php

Highlighting keywords in search results using php

Highlight keywords in search result using php, it will help to identify appropriate results easily. The below php code used to highlight multiple keyword in the search.

We are searching keyword, the keyword occurred in the title and description the below code highlight the keyword using the str_replace() function to do case insensitive string replace.

HTML Search Form

The below input box used to enter the keyword to search from the database. 


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


Search and Highlighting matched keywords.

The below PHP code is used to search keywords in the title and description. If the keyword match found we call the highlightKeywords() function to highlight the text in bold and red color.


$conn = mysqli_connect("localhost", "root", "", "neukanndo_demo");

$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 highlightingkeyword " . $queryCondition;

$result = mysqli_query($conn,$sql);

 function highlighttext($text, $keyword) {

$wordsAry = explode(" ", $keyword);

$wordsCount = count($wordsAry);

for($i=0;$i<$wordsCount;$i++) {

$highlighted_text = "<span style='font-weight:bold;color:red;'>$wordsAry[$i]</span>";

$text = str_ireplace($wordsAry[$i], $highlighted_text, $text);

 

}

return $text;

}

Download Highlighting keywords in search results using php

0 Comments

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed

>