note 33289 added to function.str-ireplace
| From: | bradhuizenga at rack1 dot php dot net | Date: | Fri, 20 Jun 2003 22:56:36 +0000 |
| Subject: | note 33289 added to function.str-ireplace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-50774@lists.php.net to get a copy of this message | ||
To the best of my knowledge this works in PHP3 & PHP4.
This is another update to the stri_replace() function I posted before. It now behaves more closely
to str_replace() in that if $find is an array and $replace is not, all items in $find will be
replaced by the string $replace. As before, if the $find array is bigger than the $replace array, it
will nullify anything it finds without a corresponding item in the $replace array. If the $replace
array is larger than the $find array, the extra items in the $replace array will be ignored.
function stri_replace($find,$replace,$string)
{
if(!is_array($find)) $find = array($find);
if(!is_array($replace))
{
if(!is_array($find)) $replace = array($replace);
else
{
// this will duplicate the string into an array the size of $find
$c = count($find);
$rString = $replace;
unset($replace);
for ($i = 0; $i < $c; $i++)
{
$replace[$i] = $rString;
}
}
}
foreach($find as $fKey => $fItem)
{
$between = explode(strtolower($fItem),strtolower($string));
$pos = 0;
foreach($between as $bKey => $bItem)
{
$between[$bKey] = substr($string,$pos,strlen($bItem));
$pos += strlen($bItem) + strlen($fItem);
}
$string = implode($replace[$fKey],$between);
}
return($string);
}
For example:
<?
$foobar = 'FoO FOO foo bAr BAR bar';
echo stri_replace(array('foo','bar'),'woggle',$foobar);
// echos 'woggle woggle woggle woggle woggle woggle'
?>
-Brad Huizenga
----
Manual Page -- http://www.php.net/manual/en/function.str-ireplace.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33289
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33289&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33289&report=yes