Str_Replace与数组大写和数字(PHP)

时间:2018-04-08 18:11:13

标签: php arrays str-replace

我有一个简单的代码,但我无法正常工作。

$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;
  • 正确的结果:ABCabc123
  • 但是我的代码返回了这个结果:123abc123!

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

str_replace将替换所有出现的字母,因此如果我们将代码拆分为2,我们可以更多地了解会发生什么:

<?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'所以'A'将被1替换两次,因此'B'替代'C'