Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Highlight Words in Search Results

When searching text for a specific keyword or keywords, it's good practice to give the user the option of deciding whether they'd like those keywords highlighted in search results. The following PHP function will highlight defined keywords in text by regular expression.

It will turn this:

Lorem ipsum dolor sit semper amet, consectetur adipiscing elit. Semper vestibulum eu nulla auctor, vehicula sem vel, suscipit lorem ligula. Quisque libero lorem, semper eget fermentum id, condimentum at turpis.

Into this:

Lorem ipsum dolor sit semper amet, consectetur adipiscing elit. Semper vestibulum eu nulla auctor, vehicula sem vel, suscipit lorem ligula. Quisque libero lorem, semper eget fermentum id, condimentum at turpis.

PHP Functions

This is the older function we used. PHP's ereg_replace() function was depreciated in version 5.3.0 meaning that it's not an ideal long-term solution.

1
<?php 
2
/*
3
    Highlight Words in Search Results    
4
    http://www.beliefmedia.com/code/php-snippets/highlight-search
5
*/
6
 
7
 
8
function beliefmedia_highlight($text, $words, $color='yellow', $case = true) {
9
 
10
 $words = trim($words); 
11
 $words_array = explode(' ', $words); 
12
 
13
 foreach($words_array as $word) { 
14
   if(strlen(trim($word)) != 0) 
15
     $text = ($case !== false) ? eregi_replace($word, '<font style="background:' . $color . '";>\\0</font>', $text) : ereg_replace($word, '<font style="background:' . $color . '";>\\0</font>', $text);
16
   }
17
 
18
 return $text; 
19
}

A more-up-to-date function is as follows.

1
<?php 
2
/*
3
    Highlight Words in Search Results    
4
    http://www.beliefmedia.com/code/php-snippets/highlight-search
5
*/
6
 
7
 
8
function beliefmedia_highlights($text, $words, $case = false) { 
9
 
10
 $words = trim($words);
11
 $words_array = explode(',', $words);
12
 
13
 $regex = ($case !== false) ? '/\b(' . implode('|', array_map('preg_quote', $words_array)) . ')\b/i' : '/\b(' . implode('|', array_map('preg_quote', $words_array)) . ')\b/';
14
 foreach($words_array as $word) { 
15
  if(strlen(trim($word)) != 0) 
16
   $text = preg_replace($regex, '<font style="background: yellow";>$1</font>', $text);
17
  } 
18
 
19
 return $text;
20
}

Both are a little old. We'll share others soon.

Example

Using the last function, use the following:

1
<?php 
2
$words = 'lorem,semper,ipsum';
3
$text = 'Lorem ipsum dolor sit semper amet, consectetur adipiscing elit. Semper vestibulum eu nulla auctor, vehicula sem vel, suscipit lorem ligula. Quisque libero lorem, semper eget fermentum id, condimentum at turpis.';
4
echo beliefmedia_highlights($text, $words, $case = false);

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment