When use str_replace with arrays there's strange behavior
var_dump(str_replace(
[
',',
'.',
],[
'.',
',',
],
'1.2,3'
));
This code is expected to replace all commas with dots and all dots with
commas, however in result we get all commas.
On Tue, May 25, 2021 at 12:13 PM Eugene Sidelnyk zsidelnik@gmail.com
wrote:
When use str_replace with arrays there's strange behavior
var_dump(str_replace( [ ',', '.', ],[ '.', ',', ], '1.2,3' ));
This code is expected to replace all commas with dots and all dots with
commas, however in result we get all commas.
str_replace()
performs the first replacement on the whole string, then the
second replacement on the whole string etc. If you want to replace all
strings "in parallel" you need to use strtr()
instead:
https://3v4l.org/tk6FO
I believe this is what the "Caution" on http://php.net/str_replace is
trying to tell you, though its phrasing is rather confusing.
Regards,
Nikita