note 107168 added to function.str-ireplace
| From: | chud37 dot com at osu1 dot php dot net | Date: | Wed, 11 Jan 2012 20:52:36 +0000 |
| Subject: | note 107168 added to function.str-ireplace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-185591@lists.php.net to get a copy of this message | ||
After searching through the forums and laboriously testing all the highlight functions (as I was too
lazy to write my own, I wanted a quick solution), I found that none of them did what I wanted at
all.
I just wanted a function that took a string and did not modify it in anyway, apart from just
surrounding the matching words with some kind of highlighting HTML. At best all the ones of the
forums here changed the text but also the case as well. The example given by sawdust *did* work
except when given a single character when it continued to loop-replace the letter 'a' in
the inserted 'background-color:'. So, here is a fool proof, no-nonsense replace method
that should work always.
<?php
function highlight($haystack, $needle) {
if (strlen($haystack) < 1 || strlen($needle) < 1) {return $haystack;}
preg_match_all("/$needle+/i", $haystack, $match);
$exploded = preg_split("/$needle+/i",$haystack);
$replaced = "";
foreach($exploded as $e)
foreach($match as $m)
if($e!=$exploded[count($exploded)-1]) {$replaced .= $e . "<font
style=\"background-color:yellow\">" . $m[0] . "</font>";} else
{$replaced .= $e;}
return $replaced;
}
?>
----
Server IP: 87.124.126.117
Probable Submitter: 178.104.164.21 (proxied: 178.104.164.21)
----
Manual Page -- http://www.php.net/manual/en/function.str-ireplace.php
Edit -- https://master.php.net/note/edit/107168
Del: integrated -- https://master.php.net/note/delete/107168/integrated
Del: useless -- https://master.php.net/note/delete/107168/useless
Del: bad code -- https://master.php.net/note/delete/107168/bad+code
Del: spam -- https://master.php.net/note/delete/107168/spam
Del: non-english -- https://master.php.net/note/delete/107168/non-english
Del: in docs -- https://master.php.net/note/delete/107168/in+docs
Del: other reasons-- https://master.php.net/note/delete/107168
Reject -- https://master.php.net/note/reject/107168
Search -- https://master.php.net/manage/user-notes.php