|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-08-09 18:31 UTC] info at maduranma dot com
Description:
------------
In the code below, if you change the first "' '" of the second array in the str_replace function with some kind of value it doesn't happen, but if you do not, it takes it to the last value of the array, that's "'0'" and you can change it to "'ssdsad'" (for example) and you'll see that it takes the last value.
Test script:
---------------
$msg = 'AABB';
$msg = str_replace(array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' '), array(' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'), $msg); // N-1
echo $msg;
Expected result:
----------------
AA
Actual result:
--------------
00AA
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 06 19:00:01 2026 UTC |
To make it easiest: $msg = 'AA '; $msg = str_replace(array('A', ' '), array(' ', 'A'), $msg); echo $msg; It gives 'AAAA' instrad of ' AA', and, if you change 'A' like this: $msg = 'AA '; $msg = str_replace(array('A', ' '), array(' ', 'A2'), $msg); echo $msg; It returns 'A2A2A2A2'IMPORTANT EDIT: It not only happens with spaces, it happens with the first value too, it does the replacement 2 times if it's the first and just the first, like you can see here: str_replace(array('A', 'B', 'C', 'O'), array('O2', 'A', 'B', 'C'), 'AABB');