|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-06-14 00:20 UTC] kloas at mail dot ru
Description:
------------
hi? im from russian? english is bad
so here code with bug
<?
$a=array("1","2","3","4","5","6","7","8","9","0");
$b=array("9","8","7","6","5","4","3","2","1","0");
$str="1234567890";
echo str_replace($a,$b,$str);
?>
////echo 1234543210
Test script:
---------------
<?
$a=array("1","2","3","4","5","6","7","8","9","0");
$b=array("9","8","7","6","5","4","3","2","1","0");
$str="1234567890";
echo str_replace($a,$b,$str);
?>
must be 0987654321
Expected result:
----------------
<?
$a=array("1","2","3","4","5","6","7","8","9","0");
$b=array("9","8","7","6","5","4","3","2","1","0");
$str="1234567890";
echo str_replace($a,$b,$str);
?>
Actual result:
--------------
<?
$a=array("1","2","3","4","5","6","7","8","9","0");
$b=array("9","8","7","6","5","4","3","2","1","0");
$str="1234567890";
echo str_replace($a,$b,$str);
?>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 06:00:01 2025 UTC |
As the docs state, if the search and replace params are arrays, their elements are processed first to last. That means it iterates over the string and does each replacement from the arrays one by one, left to right. That means you have these steps: 1234567890 Original string 9234567890 Replace all 1's with 9's 9834567890 Replace all 2's with 8's 9874567890 Replace all 3's with 7's 9876567890 Replace all 4's with 6's 9876567890 Replace all 5's with 5's 9874547890 Replace all 6's with 4's 9834543890 Replace all 7's with 3's 9234543290 Replace all 8's with 2's 1234543210 Replace all 9's with 1's If you want to translate chars in a single pass, use strtr() eg. echo strtr("1234567890","9876543210",$str);