为什么它不起作用?
这是documentation for str_replace() 中提到的替换问题:
更换订单问题
因为str_replace() 从左到右替换,它可能会替换之前插入的值
多次替换。另请参阅本文档中的示例。
您的代码相当于:
$key = 'm';
$key = str_replace('y', 'Year', $key);
$key = str_replace('m', 'Month', $key);
$key = str_replace('d', 'Days', $key);
$key = str_replace('h', 'Hours', $key);
$key = str_replace('i', 'Munites', $key);
$key = str_replace('s', 'Seconds', $key);
echo $key;
如您所见,m 被Month 替换,Month 中的h 被Hours 替换,Hours 中的s 被替换为Seconds。问题是,当您在 Month 中替换 h 时,无论字符串 Month 代表最初的 Month 还是最初的 m,您都在这样做强>。每个str_replace() 都在丢弃一些信息——原始字符串是什么。
这就是你得到这个结果的方式:
0) y -> Year
Replacement: none
1) m -> Month
Replacement: m -> Month
2) d -> Days
Replacement: none
3) h -> Hours
Replacement: Month -> MontHours
4) i -> Munites
Replacement: none
5) s -> Seconds
Replacement: MontHours -> MontHourSeconds
解决办法
解决方案是使用strtr(),因为它不会更改已替换的字符。
$key = 'm';
$search = array('y', 'm', 'd', 'h', 'i', 's');
$replace = array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds');
$replacePairs = array_combine($search, $replace);
echo strtr($key, $replacePairs); // => Month