note 69459 deleted from function.eregi-replace by nlopess
| From: | nlopess@php.net | Date: | Thu, 07 Sep 2006 11:00:48 +0000 |
| Subject: | note 69459 deleted from function.eregi-replace by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-116819@lists.php.net to get a copy of this message | ||
Note Submitter: sonicade at gmail dot com
----
I built this highlight keywords function because I needed to highlight several different keywords
within the same string. This function searchs the string character by character in order to avoid
duplicate evaluations. It also allows the user to specify the opening and closing tag of the
highlighted keyword.
<?
/*
function to highlight keywords
$string = string of characters to search for highlighted keywords
$keywords = array of keywords to highlight in $string
$hb = highlight format open tag
$he = highlight format close tag
*/
function highlight_keywords ($string,$keywords,$hb="",$he="") {
$ignore_html = true;
$rstring = "";
for ($i=0;$i<strlen($string);$i++) { // evaluate string 1 character at a time
$mkwa = array(); // reset matched keywords array
// if html break, increment position and move to next loop
if ( ($ignore_html) && (substr($string,$i,4) == "<br>") ) {
$rstring .= substr($string,$i,4); $i = $i + 3; continue; // add 3 because loop will add 1 (total
4)
}
// search through keywords for possible matchs
// if a keyword is matched, add it to the matched keywords array
foreach ($keywords as $k) {
if (strtolower(substr($string,$i,strlen($k))) == strtolower($k)) {
// store length of keyword highlight
$mkwa[] = strlen($k);
}
}
// if there are matched keywords then determine longest match
// reverse sort the list of matched keyword lengths
if (sizeof($mkwa) > 0) {
rsort($mkwa);
$rstring .= $hb.substr($string,$i,$mkwa[0]).$he;
$i = $i + ($mkwa[0] - 1); // subtract 1 because loop will add 1 (total length)
}
else if ($i <= strlen($string)) { $rstring .= $string[$i]; } // if $i is not out of bounds, add
character
}
return $rstring;
}
// example
$mystring = "the quick brown fox";
$mykeywords = array('quick','fox');
echo highlight_keywords($mystring, $mykeywords, "<b>", "</b>");
?>