-1

I have a simple code but i cant do it works fine.

$String = 'abc123ABC';

$Replace_From = array("a","b","c","1","2","3","A","B","C");
$Replace_To   = array("A","B","C","a","b","c","1","2","3");

$NewString = str_replace($Replace_From, $Replace_To, $String);
echo $NewString;
  • The correct result its: ABCabc123
  • But my code return this result: 123abc123 !

Thanks you for your help!

Jose
  • 401
  • 4
  • 15
  • 1
    Use [strtr()](http://php.net/manual/en/function.strtr.php) instead; and understand the difference in how they work – Mark Baker Apr 08 '18 at 18:13

1 Answers1

0

str_replace will replace all occurrences of the letter, so if we split the code in 2 we could understand more what happens:

<?php
$String = 'abc123ABC';

$Replace_From = array("a","b","c","1","2","3");
$Replace_To   = array("A","B","C","a","b","c");

$FirstString = str_replace($Replace_From, $Replace_To, $String);
echo $FirstString . '<br>';

$Replace_From = array("A","B","C");
$Replace_To   = array("1","2","3");

$SecondString = str_replace($Replace_From, $Replace_To, $FirstString);
echo $SecondString;

$FirstString = 'ABCabcABC' So 'A' will be replaced by 1 two times and so for 'B' and so for 'C'.

Ermac
  • 1,181
  • 1
  • 8
  • 12