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

18 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

  14. P.Arul says:

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

Leave a comment