PHP highlight search keywords

PHP highlight search keywords

Friday, April 11th, 2008 in PHP

php highlight keywords While performing a search, it’s ofter very useful to highlight in different colors, backgrounds or styles the search keywords in the results returned. This keeps focus on the keywords and helps scan the page faster to find the more relevant results.

But how exactly can that be done? As a basic idea, the following code ( a PHP class ) practically takes as parameters the text that needs to be highlighted and the particular keywords that need to stand out. Using a regular expression, every keyword in the text is replaced with a span HTML element having different styles applied according to the keyword it matches.

Please remember that the code below is just an example, it can be and should be extended; I’m only presenting it for demonstration and “how to” purposes.

The class is made out of 3 methods: the class constructor, the hex color generator and a RGB to hex helper function. All the keywords highlighting is done in the class constructor that calls the hex color generator or the colors and than saves the highlighted text into the output variable.

But enough talk. Here’s the full code for highlighting the search keywords in a page based on what a user might be looking for on your website.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
    $text = 'Lorem ipsum dolor sit amet, consectetuer
adipiscing elit. Vestibulum blandit mollis risus.';
 
    class highlight
    {
        public $output_text;
 
        function __construct($text, $words)
        {
            $split_words = explode( " " , $words );
            foreach ($split_words as $word)
            {
                $color = self::generate_colors();
                $text = preg_replace("|($word)|Ui" ,
                           "<span style=\"background:".$color.";\"><b>$1</b></span>" , $text );
            }
            $this->output_text = $text;
        }
 
        private function rgbhex($red, $green, $blue)
        {
            return sprintf('#%02X%02X%02X', $red, $green, $blue);
        }
 
        private function generate_colors()
        {
            $red = rand( rand(60,100) , rand(200,252) );
            $green = rand( rand(60,100) , rand(200,252) );
            $blue = rand( rand(60,100) , rand(200,252) );
 
            $color = self::rgbhex( $red , $green , $blue );
            return $color;
        }
    }
 
    $highlight = new highlight($text , 'lorem dolor blandit');
    echo $highlight->output_text;
?>

That would be it. This can be used in various ways: to highlight search from the search form of your own website or to highlight keywords for users that come from Google, Yahoo or other web search engine.

Was this useful? Show your support.

digg PHP highlight search keywords

34 comments

  1. Gaurav says:

    Great stuff helped me a lot
    Thnx

  2. lanci says:

    If I write it:

    $ob = new highlight($text,”background padding lorem”);

    echo$ob->output_text;

    what happens?

  3. You have a point here. If the text you’re highlighting has HTML markup, it will create a mess. I developed this script for plain text so a solution would be to use strip_tags() on the text and after that do the highlighting.

  4. dany says:

    If the keyword being searched for has a single character after a word. e.g. “apple a”, I end up with html highlighting all the a’s in the text.

    could you tell me how to fix this,

    by the way, the script is the best I’ve found on the net
    Thanks!

    • Hi Dany,

      This happens because the script highlights all words you entered, in this case “apple” and “a”. One thing you could do is check string length and apply highlight only if word has more than x letters ( x being the minimum number of letters you want the script to consider a word ).

  5. dany says:

    Thank you Constantin for replying.

    the problem was thats php displayed letters within the & tags before the $1 variable.

    Thanks again!

  6. krisna ramadugula says:

    It’s great ..thanks a lot..i modified this code like this,to hilight the search word in yellow colour
    <?php
    $text = 'Lorem ipsum dolor sit amet, consectetuer
    adipiscing elit. Vestibulum blandit mollis risus.';
    class highlight
    {
    public $output_text;
    function __construct($text, $words)
    {
    $split_words = explode( " " , $words );
    foreach ($split_words as $word)
    {
    $color= '#FFFF00';
    $text = preg_replace("|($word)|Ui" ,
    "$1” , $text );
    }
    $this->output_text = $text;
    }

    }
    $highlight = new highlight($text , ‘lorem dolor blandit ipsu’);
    echo $highlight->output_text;
    ?>

  7. Wow! terrific!

    Thanks for sharing your knowledge with us!

  8. Diro says:

    Hi all,
    first of all, thanks for the great tips, i’m just curious where this script place on to…
    Thanks all

  9. uma says:

    @ krisna ramadugula
    good work there,but unfortunately doesn work for me…
    one doubt here,where is the $color used in this program,

    output_text = $text;
    }

    }
    $highlight = new highlight($text , ‘lorem dolor blandit ipsu’);
    echo $highlight->output_text;
    ?>

  10. UMA says:

    i just figured this out…..if we try to search a string in uppercase ,the original string changes to upper case:(

    <?php
    $text = 'hello azma how are you azma.';
    class highlight
    {
    public $output_text;
    function __construct($text, $words)
    {
    $split_words = explode( " " , $words );
    //print_r($split_words);
    foreach ($split_words as $word)
    {
    //echo $word;
    $color= "”.$word.”";
    $text = preg_replace(“|($word)|Ui” ,$color , $text );
    }
    $this->output_text = $text;
    }
    }
    $highlight = new highlight($text , “ARE YOU AZMA”);
    echo $highlight->output_text;

    ?>

  11. UMA says:

    Mr Boiangiu,Please can you help me with the above one…

    • This happens because words in string get replaced with words from query. So if your user enters words in uppercase, words in your text will be replaced by the uppercase version from query. You could make the search case sensitive by removing the i in preg_replace ( preg_replace(“|($word)|U”… )

  12. UMA says:

    Thanks :)

  13. EL says:

    Can I use this code with a database search?

    Thanks

    • Yes you can. Instead of that bogus text just put what your database query returns.

    • Andrew says:

      Hi guys! First of all, good work! I’m trying to create a similar code, with str_replace. I don’t know exactly what the difference is, but i does no matter. The Problem I have, and this code has also, (and haven’t found a solution for this yet), if you type in some of the following keywords: span, style, backgroung etc. the result breaks. For example:
      $highlight = new highlight($text , ‘lorem dolor back’);
      it’s a big problem i think. And it is caused by the foreach() function.
      First it replaces the words ‘lorem’ to: lorem
      Then it searches the word ‘back’ and replaces it, but it searches in the previous text with the HTML tags.
      So the result HTML code is that:
      <span style=\"background:#AD7CA7;\”>lorem

      If you have some soluton please share with me, Thanks

      • Hmm, no solution for that yet. This is a very old example about what can be done with regular expressions and it’s for demo purposes only. I’ll try and expand that a little, but this will probably happen during the next year, enjoying holidays now.

      • Pertneer says:

        This solution seams to have resolved your issue. If you concatenate the string into a new string you eliminate the issue of searching through the new html text that you create in the foreach loop. Then I cleared the $text to prevent any other unforeseen issues.

        class highlight
        {
        public $output_text;

        function __construct($text, $words)
        {
        $split_words = explode( ” ” , $words );
        $output = “”;
        foreach ($split_words as $word)
        {
        $color = self::generate_colors();
        if(strlen($word) < 3){

        }else{
        $text = preg_replace("|($word)|Ui" , "$1” , $text );
        }
        $output .= $text;
        $text = “”;
        }
        $this->output_text = $output;
        }

        private function rgbhex($red, $green, $blue)
        {
        return sprintf(‘#%02X%02X%02X’, $red, $green, $blue);
        }

        private function generate_colors()
        {
        $red = rand( rand(60,100) , rand(200,252) );
        $green = rand( rand(60,100) , rand(200,252) );
        $blue = rand( rand(60,100) , rand(200,252) );

        $color = self::rgbhex( $red , $green , $blue );
        return $color;
        }
        }

  14. P.Arul says:

    I want the php script with alias search highlight liks ‘_’ and ‘%’

  15. Nirmal Patel says:

    great post.

    Thanks for sharing. :-)

  16. Gr8… I m searching of actually this

  17. [...] de termes trobats als posts retornats. Per aconseguir-ho s’ha implementat la classe highlight del web [...]

  18. Andy Marks says:

    Great post. One item I needed to add for my site was to ensure ONLY full words were highlighted. I accomplished this by modifying:

    $text = preg_replace(“|($word)|Ui” ,
    $1” , $text );

    to:

    $text = preg_replace(“|(\b$word\b)|Ui” ,
    $1” , $text );

    there are three edits. adding \b before and after $word are the first and second edit. lastly, placing a space before $1.

    Thanks again for the class, works wonders.

  19. lisam says:

    how can i make this happen to a table listing search?
    like when i use while() statement, then the result shows in a table with so many rows.

    help :(

  20. bystwn22 says:

    i know its old topic but, its for newers
    i just edited and fixed the search highlight problem, now its work with html
    class highlight {
    public $output_text;
    function __construct($text, $words) {
    $split_words = explode(” “, $words );
    foreach ($split_words as $word) {
    $color = self::generate_colors();
    $color2 = self::generate_colors2();
    $text = preg_replace(“|\b($word)\b|se”, ‘”$1“‘, $text );
    }
    $this->output_text = $text;
    }

    private function rgbhex($red, $green, $blue) {
    return sprintf(‘#%02X%02X%02X’, $red, $green, $blue);
    }

    private function generate_colors() {
    $red = rand( rand(200,252) , rand(200,252) );
    $green = rand( rand(200,252) , rand(200,252) );
    $blue = rand( rand(200,252) , rand(200,252) );

    $color = self::rgbhex( $red , $green , $blue );
    return $color;
    }
    private function generate_colors2() {
    $red = rand( rand(40,100) , rand(100,252) );
    $green = rand( rand(40,100) , rand(100,252) );
    $blue = rand( rand(40,100) , rand(100,252) );

    $color = self::rgbhex( $red , $green , $blue );
    return $color;
    }
    }

  21. Benjamin says:

    This tutorial is definitely the best I’ve seen for highlighting search strings in search results because it actually replaces the strings with the correct casing. Many of the other methods I’ve seen online replace the result text with the casing that was typed in the search.

    The only issue I had to deal with was if someone started typing nothing but spaces. It gets a little crazy.

  22. Imre says:

    Can you tell me how can I get the keywords that the user searched for e.g. with google when hit my site? I’d like to highlight those.

  23. krzydyn says:

    Hi,
    I figured out little simpler:

    	function highlight($txt,$words){
    		if (!is_array($words))
    			$words=preg_split("/[^[:alpha:]]+/",$words);
    		$words=array_unique($words);
    		$repl=array();
    		for ($i=0; $i<sizeof($words); ++$i)
    			$repl[$i]="<span class=\"hi\">".$words[$i]."</span>";
    		return str_ireplace($words,$repl,$txt);
    	}
    

Leave a comment