I need to highlight a keyword in a paragraph, as google does in its search results. Let\'s assume that I have a MySQL db with blog posts. When a user searches for a certain
I found this post when doing a search for how to highlight keyword search results. My requirements were:
I am fetching my data from a MySQL
database, which doesn't contain elements, by design of the form which stores the data.
Here is the code I found most useful:
$keywords = array("fox","jump","quick");
$string = "The quick brown fox jumps over the lazy dog";
$test = "The quick brown fox jumps over the lazy dog"; // used to compare values at the end.
if(isset($keywords)) // For keyword search this will highlight all keywords in the results.
{
foreach($keywords as $word)
{
$pattern = "/\b".$word."\b/i";
$string = preg_replace($pattern,"<span class=\"highlight\">".$word."</span>", $string);
}
}
// We must compare the original string to the string altered in the loop to avoid having a string printed with no matches.
if($string === $test)
{
echo "No match";
}
else
{
echo $string;
}
Output:
The <span class="highlight">quick</span> brown <span class="highlight">fox</span> jumps over the lazy dog.
I hope this helps someone.