note 33288 deleted from function.str-replace by aidan
| From: | aidan@php.net | Date: | Fri, 25 Jun 2004 06:06:42 +0000 |
| Subject: | note 33288 deleted from function.str-replace by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71640@lists.php.net to get a copy of this message | ||
Note Submitter: bradhuizenga at softhome dot net
----
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