|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-01-28 18:56 UTC] 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(" ", "&"),
"Hello & goodbye!"
);
This should replace "Hello & goodbye!" with "Hello & goodbye!" but it actually results in "Hello&nbsp&&nbspgoodbye!", as the original replacement of " " with " " introduced an additional ampersand.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 10:00:02 2025 UTC |
Jani, The documentation says "This function returns a string or an array with all occurrences of search in subject replaced with the given replace value." Refer to the following example: $subject = 'A'; echo str_replace( array('A','B','C','D'), array('B','C','D','E'), $subject); The result is 'E'. If str_replace() is replacing occurrences in *$subject*, then how do we end up with 'E' if 'D' doesn't exist in $subject? The result SHOULD be 'B'. $subject is 'A', so the first replacement replaces 'A' with 'B'. The second replacement, as the documentation states, should check for occurrences of 'B' within $subject, *NOT* within str_replace('A', 'B', $subject) - and so on. If this result is not a bug, then the documentation should be updated to indicate that subsequent replacements are done on the result of the previous replacement operation. Thanks