我需要使用 str_replace 替换多个值。
这是我要替换的 PHP 代码。
$date = str_replace(
array('y', 'm', 'd', 'h', 'i', 's'),
array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'),
$key
);
当我在 $key
中传递 m
时,它返回类似的输出。
MontHours
当我在 $key
中传递 h
时,它返回输出。
HourSeconds
它返回这个值我只想要 Month
。
为什么不起作用?
这是 documentation for str_replace()
中提到的一个替换陷阱:
Replacement order gotcha
Because str_replace()
replaces left to right, it might replace a previously inserted value when doing
multiple replacements. See also the examples in this document.
你的代码等同于:
$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