Highlight specific words in a phrase with PHP

You may use this code to highlight specific words in your displaying search results.

    <?php
	/* Source: http://www.apphp.com/index.php?snippet=php-highlight-specific-words-in-a-phrase */	
    function highlight($str, $words){
        if(!is_array($words) || empty($words) || !is_string($str)){
            return false;
        }
        $arr_words = implode('|', $words);
        return preg_replace(
            '@\b('.$arr_words.')\b@si',
            '<strong style="background-color:yellow">$1</strong>',
            $str
        );
    }
    ?>

Usage


Comments

Add your comment