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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
We can match exactly 3 letters like this:
…and we’ll need it to be case insensitive:
…so the first part is just:
Next, we need to match either 1 or 2 numerics. A numeric can be represented with the escape sequence
\d, so we’d use:Next we match the time string, using the same escape sequence:
…followed by a final 4 digit year:
Put it all together and we get:
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 frompreg_replace_callback(). But,preg_replace()gives us theemodifier 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 PHPeval(), but this is a legitimate use case.So our final PHP code looks like this:
See it working