PHP: preg replace date time

php, preg-replace

Solution

Well, what you need is an expression that will match 3 letters (`Fri`) followed by a space and another three letters (`Mar`).

First we need to match some letters:

/[a-z]/

We can match exactly 3 letters like this:

/[a-z]{3}/

...and we'll need it to be case insensitive:

/[a-z]{3}/i

...so the first part is just:

/[a-z]{3} [a-z]{3}/i

Next, we need to match either 1 or 2 numerics. A numeric can be represented with the escape sequence `\d`, so we'd use:

/\d{1,2}/

Next we match the time string, using the same escape sequence:

/\d{2}:\d{2}:\d{2}/

...followed by a final 4 digit year:

/\d{4}/

Put it all together and we get:

/[a-z]{3} [a-z]{3} \d{1,2} \d{2}:\d{2}:\d{2} \d{4}/i
// Fri       Mar      23     15 :  21 :  08    2012

Now, we need to replace it with the current date and time. The usual place we'd go for that is the `date()` function, but how to we get that into the replacement dynamically? Well we could pass it as a string literal, or we could use a callback function to get it from `preg_replace_callback()`. But, `preg_replace()` gives us the `e` modifier which causes the replacement string to be evaluated for PHP code. We have to be careful and sparing with it's use, as with any PHP `eval()`, but this is a legitimate use case.

So our final PHP code looks like this:

preg_replace(
  '/[a-z]{3} [a-z]{3} \d{1,2} \d{2}:\d{2}:\d{2} \d{4}/ie',
  "date('D M j H:i:s Y')",
  $str
);

See it working

Problem

how can i replace date/time in this format 'Fri Mar 23 15:21:08 2012' with preg_replace? Date in this format is present couple of times in my text and i need to replace it with current time/date. Thanks, Chris

Original source