php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #55051 bag with function str_replace
Submitted: 2011-06-14 00:20 UTC Modified: 2011-06-14 05:15 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: kloas at mail dot ru Assigned:
Status: Not a bug Package: PHP options/info functions
PHP Version: 5.3.6 OS: win 7
Private report: No CVE-ID: None
 [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);

?>

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-06-14 05:15 UTC] rasmus@php.net
-Status: Open +Status: Bogus
 [2011-06-14 05:15 UTC] rasmus@php.net
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);
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 18:01:29 2024 UTC