note 88541 rejected from function.str-replace by thiago

From: Date: Wed, 28 Jan 2009 17:11:38 +0000
Subject: note 88541 rejected from function.str-replace by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-149895@lists.php.net to get a copy of this message
Note Submitter: michael dot moussa at gmail dot com ---- As previous commentators mentioned, there is a bug with str_replace(...) when $search and $replace are arrays in that it factors previous replacements into the process rather than operating solely on the original string as is expected. Sample: <?php $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); echo str_replace($search, $replace, 'ABCDE'); // output: 'FFFFFF' ?> In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet. The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'. The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to work around this bug. <?php /** * String replacement function designed to work around the bug in str_replace(...) when working with * arrays. In str_replace(...), values that did not exist in the original string (but were put there * by previous replacements) will be replaced continuously and result in unexpected output. * * @param array $search list of strings or characters that need to be replaced * @param array $replace list of strings or characters that will replace the corresponding values in $search * @param string $subject the string on which this operation is being performed * * @return string $subject with all substrings in the $search array replaced by the values in the $replace array */ function stro_replace($search, $replace, $subject) { return strtr( $subject, array_combine($search, $replace) ); } $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); echo stro_replace($search, $replace, 'ABCDE'); // output: 'BCDEF' ?> Another example: <?php $search = array('ERICA', 'AMERICA'); $replace = array('JON', 'PHP'); $subject = 'MIKE AND ERICA LIKE AMERICA'; // We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP" echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct ?>

« previous php.notes (#149895) next »