note 42841 added to function.preg-replace
| From: | cfristrupathotmail at rn2 dot php dot net | Date: | Mon, 31 May 2004 18:37:51 +0000 |
| Subject: | note 42841 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-70359@lists.php.net to get a copy of this message | ||
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;
}
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42841
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42841&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42841&report=yes
Search -- http://master.php.net/manage/user-notes.php