note 42075 deleted from function.ereg-replace by kennyt

From: Date: Wed, 26 Jan 2005 03:54:40 +0000
Subject: note 42075 deleted from function.ereg-replace by kennyt
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-83984@lists.php.net to get a copy of this message
Note Submitter: email at webmasterbrain dot com ---- This function will replace each iteration of the same pattern with the next value in the array: <? function eregi_array_replace($pattern,$string,$replace_array) { for($x = 0;eregi($pattern,$string,$match);$x++) { $current_match = $match[0]; $start = strpos($string,$current_match); $length = strlen($current_match); $substring = substr($string,$start,$length); if(@!$replace_array[$x]) $x = 0; $substring = eregi_replace($pattern,$replace_array[$x],$substring); $start = strpos($string,$current_match,$start); $string = substr_replace($string,$substring,$start,$length); } return $string; } $replace = array('apples','bananas','pears'); $string = 'Do you sell fruit, fruit, and fruit? Yes, we sell fruit, fruit, and fruit.'; #Output: #Do you sell apples, bananas, and pears? #Yes, we sell apples, bananas, and pears. echo eregi_array_replace('fruit',$string,$replace); ?> If there are more matches than replacements it will begin again at the start of the array It might not be a perfect function, but it did what I needed, and someone might find it useful. -- The Brain http://www.webmasterbrain.com/

« previous php.notes (#83984) next »