note 33288 added to function.str-replace

From: Date: Fri, 20 Jun 2003 22:53:58 +0000
Subject: note 33288 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-50773@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-replace.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33288 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33288&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33288&report=yes

« previous php.notes (#50773) next »