#47232 [Opn->Bgs]: str_replace() factors previous replacements into process

From: Date: Wed, 28 Jan 2009 22:47:13 +0000
Subject: #47232 [Opn->Bgs]: str_replace() factors previous replacements into process
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-133276@lists.php.net to get a copy of this message
ID: 47232 Updated by: jani@php.net Reported By: michael dot moussa at gmail dot com -Status: Open +Status: Bogus Bug Type: Strings related Operating System: * PHP Version: 5.2.8 New Comment: Maybe this is a bit confusing but I do understand it exactly like that: "If search or replace are arrays, their elements are processed first to last." So in: a b c d e b c d e f 1st pass: b b c d e 2nd pass: c c c d e 3rd pass: d d d d e 4th pass: e e e e e 5th pass: f f f f f If it did not work like it does, it would not do what it's expected to do. Use preg_replace() instead with proper regexps. str_replace() is the quick'n' dirty method.. Previous Comments: ------------------------------------------------------------------------ [2009-01-28 18:56:10] michael dot moussa at gmail dot com Description: ------------ When $search and $replace are arrays, str_replace factors previous replacements into the process and produces unexpected input. Reproduce code: --------------- <?php $search = array('A', 'B', 'C', 'D', 'E'); $replace = array('B', 'C', 'D', 'E', 'F'); echo str_replace($search, $replace, 'ABCDE'); ?> Expected result: ---------------- Each letter in the string 'ABCDE' should be replaced by the letter that follows it in the alphabet, that is, A should be replaced with B, B should be replaced with C, etc... The expected result is 'BCDEF' Actual result: -------------- The actual result is 'FFFFF'. The documentation does not indicate that $subject is continuously updated as the process moves along. A more practical example: echo str_replace( array(" ", "&"), array("&nbsp", "&amp;"), "Hello & goodbye!" ); This should replace "Hello & goodbye!" with "Hello&nbsp;&amp;&nbsp;goodbye!" but it actually results in "Hello&amp;nbsp&amp;&amp;nbspgoodbye!", as the original replacement of " " with "&nbsp;" introduced an additional ampersand. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=47232&edit=1

« previous php.bugs (#133276) next »