note 42841 deleted from function.preg-replace by tomsommer
| From: | tomsommer@php.net | Date: | Mon, 31 May 2004 18:43:37 +0000 |
| Subject: | note 42841 deleted from function.preg-replace by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-70360@lists.php.net to get a copy of this message | ||
Note Submitter: cfristrup at hotmail
----
A function to highlight words inside a html document by inserting a <span
class="highlight"></span> around the word.
The function only match words outside html tags and outside the head, script and textarea areas.
function Highlight($words,$text)
{//By CF 2004
//make sure words is an array
if (!is_array($words))
$words[]=$words;
//make search and replace patterns
foreach ($words as $value)
{
$pattern[]="/(>[^<]*?)($value)/si";
$replace[]='\\1<span class="highlight">\\2</span>';
}
//Do not want to search and replace inside <head> <script> and <textarea> areas.
if (preg_match_all(
"'<(head|script|textarea)[^>]*?>.*?</\\1[^>]*?>'si",
$text, $nosearch))
{
//only want the contents of the preg_match_all
$nosearch=$nosearch[0];
reset($nosearch);
//Next split the text according to the tags
$parts=preg_split(
"'<(head|script|textarea)[^>]*?>.*?</\\1[^>]*?>'si",
$text);
//now search and replace all parts
foreach ($parts as $value)
{
//add an '>' to make sure the first part of the string get searched as well.
$temp=preg_replace($pattern,$replace,'>'.$value);
//remove the '>'
$result.=substr($temp,1);
//insert the matches from the preg_match_all
$result.=current($nosearch);
next($nosearch);
}
}
else
{
//no matching parts, so an easy case. Just 1 search and replace needed.
$result=preg_replace($pattern,$replace,'>'.$text);
$result=substr($result,1);
}
return $result;
}