How to highlight the keyword in the string and search result using php

In this tutorial We’ll talk about How to highlight the keyword in the string and search result using php, It’ll help you to focus on search keyword input by user. With the help of this quick php function you can easily highlight matched word as full keyword in search result. You can simply copy and paste following function in your php file and make it actionable. You only need to pass text and keyword which you want to make highlight.
highlight-keyword



Following is the PHP function to highlight the keyword in the string.

function highlightKeywords($keyword, $text) {
	if(isset($keyword) && !empty($keyword)) {
		return preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b style='color:blue'>$0</b>", $text);
	} else {
		return false;
	}
}
$text = "<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s";
echo highlightKeywords('Lorem', $text);

The above function uses preg_replace to replace matched keyword with some CSS Where \w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword. So As recommendation use preg_quote to escape the keyword.

See live demo and download source code.

DEMO || DOWNLOAD



Posted in: PHP

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.