PHP replace multiple value using str_replace?

Renish Khunt

I need to replace multiple value using str_replace.

This is my PHP code fore replace.

$date = str_replace(
       array('y', 'm', 'd', 'h', 'i', 's'),
       array('Year', 'Month', 'Days', 'Hours', 'Munites', 'Seconds'),
       $key
    );

When i pass m in $key it return output like.

MontHours

When i pass h in $key it return output.

HourSeconds

it return this value i want the Month only.

PleaseStand

From the manual page for str_replace():

Caution

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.

For example, "m" is replaced with "Month", then the "h" in "Month" is replaced with "Hours", which comes later in the array of replacements.

strtr() doesn't have this issue because it tries all keys of the same length at the same time:

$date = strtr($key, array(
    'y' => 'Year',
    'm' => 'Month',
    'd' => 'Days',
    'h' => 'Hours',
    'i' => 'Munites', // [sic]
    's' => 'Seconds',
));

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related