PHP replace multiple value using str_replace?

Loading

The solution

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 Monthyou’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.

$key = 'm';
$search = ['y', 'm', 'd', 'h', 'i', 's'];
$replace = ['Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'];

$replacePairs = array_combine($search, $replace);
echo strtr($key, $replacePairs); // => Month

About Post Author