note 69459 added to function.eregi-replace

From: Date: Wed, 06 Sep 2006 21:00:29 +0000
Subject: note 69459 added to function.eregi-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-116778@lists.php.net to get a copy of this message
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>"); ?> ---- Server IP: 66.163.161.117 Probable Submitter: 63.207.1.130 ---- Manual Page -- http://www.php.net/manual/en/function.eregi-replace.php Edit -- https://master.php.net/note/edit/69459 Del: integrated -- https://master.php.net/note/delete/69459/integrated Del: useless -- https://master.php.net/note/delete/69459/useless Del: bad code -- https://master.php.net/note/delete/69459/bad+code Del: spam -- https://master.php.net/note/delete/69459/spam Del: non-english -- https://master.php.net/note/delete/69459/non-english Del: in docs -- https://master.php.net/note/delete/69459/in+docs Del: other reasons-- https://master.php.net/note/delete/69459 Reject -- https://master.php.net/note/reject/69459 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#116778) next »