Why doesn't it work?
This is a replacement gotcha which is mentioned in the 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.
Your code is equivalent to:
$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;
As you can see m
gets replaced with Month
, and h
in Month
gets replaced with Hours
and the s
in Hours
gets replaced with Seconds
. The problem is that when you're replacing h
in Month
, you're doing it regardless of whether the string Month
represents what was originally Month
or what was originally an m
. Each str_replace()
is discarding some information — what the original string was.
This is how you got that result:
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
The solution
The solution would be to use strtr()
because it won't change already replaced characters.
$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