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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: kloas at mail dot ru
New email:
PHP Version: OS:

 

 [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: Fri Mar 29 02:01:30 2024 UTC