Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: preg replace date time

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

like image 444
Chris Avatar asked Dec 22 '25 11:12

Chris


2 Answers

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

like image 183
DaveRandom Avatar answered Dec 24 '25 01:12

DaveRandom


I think listing the finite sets of options is kind of better for these task and it will also save you from false positives. These are the patterns to match each part of the date format:

  • Days: (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)
  • Months: (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
  • Day: \d{1,2}
  • Time: \d{1,2}:\d{2}:\d{2}
  • Year: \d{4}

Putting everything together:

(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d{1,2}:\d{2}:\d{2} \d{4}

The code might look like:

$current_date = date('D M j H:i:s Y');
$text = preg_replace(
  '/(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d{1,2}:\d{2}:\d{2} \d{4}/i',
  $current_date,
  $text
);

See a working example.

like image 20
Alexander Avatar answered Dec 24 '25 00:12

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!