Flipkart

Thursday, June 17, 2010

Highlight Search Words

String Manipulation

This first method will highlight all the occurances of the string and is case sensitive. It uses str_replace to do the required manipulation but has faults in not being able to tell the difference between PHP and PHPRO. It will highlight the text "PHP" and "PHP"RO which may be the desired result.


<?php

/** 
 * 
 * @highlight words 
 * 
 * @param string $string 
 * 
 * @param array $words 
 * 
 * @return string 
 * 
 */
 
function highlightWords($string$words)
 {
    foreach ( 
$words as $word )
    {
        
$string str_ireplace($word'<span class="highlight_word">'.$word.'</span>'$string);
    }
    
/*** return the highlighted string ***/
    
return $string;
 }

/*** example usage ***/
$string 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
/*** an array of words to highlight ***/
$words = array('php''sql');
/*** highlight the words ***/
$string =  highlightWords($string$words);

?>

<html>
<head> 
<title>PHPRO Highlight Search Words</title> 
<style type="text/css">
.highlight_word{
    background-color: pink;
}
</style> 
</head>
<body>
 <?php echo $string?>
</body>
</html>

Regular Expression

This second method makes us of PHP PCRE to achieve a better result. The seach is case insensitive, which means it will match php and PHP. This method has the added benifit of being able to use word boundries which enables highlighting of the word PHP but not PHPRO. The word boundary prevents partial matching of the search text and of highlighting parts of words. If this is the functionality you require, this is the method to choose.


 <?php

/**
 * @highlight words
 *
 * @param string $text
 *
 * @param array $words
 *
 * @return string
 *
 */
function highlightWords($text$words)
{
        
/*** loop of the array of words ***/
        
foreach ($words as $word)
        {
                
/*** quote the text for regex ***/
                
$word preg_quote($word);
                
/*** highlight the words ***/
                
$text preg_replace("/\b($word)\b/i"'<span class="highlight_word">\1</span>'$text);
        }
        
/*** return the text ***/
        
return $text;
}


/*** example usage ***/
$string 'This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite';
/*** an array of words to highlight ***/
$words = array('php''sql');
/*** highlight the words ***/
$string =  highlightWords($string$words);

?>

<html>
<head>
<title>PHPRO Highlight Search Words</title>
<style type="text/css">
.highlight_word{
        background-color: pink;
}
</style>
</head>
<body>
 <?php echo $string?>
</body>
</html>

No comments:

Post a Comment