note 42075 added to function.ereg-replace

From: Date: Sun, 02 May 2004 15:30:34 +0000
Subject: note 42075 added to function.ereg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-69109@lists.php.net to get a copy of this message
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/ ---- Manual Page -- http://www.php.net/manual/en/function.ereg-replace.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+42075 Delete -- http://master.php.net/manage/user-notes.php?action=delete+42075&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+42075&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#69109) next »