Question

I have a string that represents a day of the week "U", "M", "T", etc". I'm trying to use preg_replace to replace the letter with the actual day name, like Sunday, Monday, etc.

However, it appears to be applying the array of replacements in an iterative fashion, which isn't what the documentation appears to specify. Any ideas?

$input = "U";
$nice_day_name = preg_replace(['/U/','/M/','/T/','/W/','/R/','/F/','/S/'],
   ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
   $input);

// Outputs "Satun", should be "Sun"
Was it helpful?

Solution 2

This task is better accomplished using strtr:

$replacements = [
    "U"=>"Sun",
    "M"=>"Mon",
    "T"=>"Tue",
    "W"=>"Wed",
    "R"=>"Thu",
    "F"=>"Fri",
    "S"=>"Sat"
];
$nice_day_name = strtr($input,$replacements);

OTHER TIPS

The documentation seems to be ambiguous. Here's what it says on the subject:

If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart.

It looks like you're reading this as "the original string will be checked for each pattern in the array, and the replacement will be made". I can see how one would read it that way. What it seems to be doing instead is checking each pattern against the string, including any replacements already made.

So it's doing this:

  1. Check the first pattern, /U/, find a match, make the replacement --> Sun
  2. Check a bunch more, find no match
  3. Check the last one, /S/, find a match (the first character), make the replacement --> Satun

To fix this, you can include the start/end character in each pattern:

['/^U$/','/^M$/','/^T$/','/^W$/','/^R$/','/^F$/','/^S$/']

This will result in a match only if the string is one character long.

Don't make the problem harder than it should be:

$day_names = array_combine(
    ['U','M','T','W','R','F','S'],
    ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
);

$nice_day_name = $day_names[$input];

str_replace() has the same issue, and I cover this in my answer to a different question.

Live demo

Try this:

$string = 'U';
$trans = array("U" => "Sun", "M" => "Mon", "T" => "Tue", "W" => "Wed", "R" => "Thu",
 "F" => "Fri", "S" => "Sat");
$result = strtr($string,$trans);
echo $result;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top