Sunday, July 23, 2017

Highlighting Text with PHP


In this tutorial, we will make a function that will highlight a keyword from a sentence. Some time recently, most developers and other individuals used to highlight searched word in a string with the utilization of inline CSS (Cascading Style Sheet) styling.

$str = "The monkey hangs on the door";
$keyword = "the";
echo str_ireplace($keyword, ''.$keyword.'', $str);






The issue with this approach was that the resulting highlighted term utilizes the capitalisation of the search word, as opposed to the instance of the original string. In the case above, the primary word "The" in the string would show up as a lower-case "the".

Here's a better way PHP function for highlighting keyword

$string = "The monkey hangs from the door";
$keyword = "the";
 
function highlightkeyword($str, $search) {
    $highlightcolor = "#daa732";
    $occurrences = substr_count(strtolower($str), strtolower($search));
    $newstring = $str;
    $match = array();
 
    for ($i=0;$i<$occurrences;$i++) {
        $match[$i] = stripos($str, $search, $i);
        $match[$i] = substr($str, $match[$i], strlen($search));
        $newstring = str_replace($match[$i], '[#]'.$match[$i].'[@]', strip_tags($newstring));
    }
 
    $newstring = str_replace('[#]', '', $newstring);
    $newstring = str_replace('[@]', '', $newstring);
    return $newstring;
 
}




That is better, utilizing this function, the matched keywords now have correct capitals.


To break down what is going on here:


  1. The parameter $occurrences counts the number of cases of the keyword are in the string utilizing substr_count. Since substr_count is not case sensitive, we initially need to change over both string and search word to lower-case
  2. An array $match is characterized to monitor each coordinated catchphrase
  3. A for loop is characterized to emphasize through the quantity of instances the keyword shows up in the string. The position in the string of the search word is calculated using stripos (case insensitive string position) and the matched word is selected using substr and the length of the keyword. Another string is then formed using str_replace (this time case sensitive), attaching the wildcard characters [#] and [@] around each matched word
  4. These trump card characters are then swapped by inline styling for the highlight. We would prefer not to incorporate the inline styles in the for loop, as the characters in the styling may match the keyword
  5. The new string is then returned


Well, simple yet useful, right? Try using this function to create a dynamic function to highlight text on your website :)







No comments:

Post a Comment

PHP IMAP - Get Emails from GMAIL

Fetching emails from your GMIAL account is easier than what you expected. With the use of PHP IMAP Extension, you can easily fetch your e...