简体   繁体   中英

regular expression replace date format in php

I'd like to use regular expression for replacing date format from string in PHP.

I have a string like this:

TEXT TEXT TEXT {POST_DATE,m/d/Y} TEXT TEXT TEXT

I want to replace all strings contain {POST_DATE,m/d/Y} by a date that get from a external function, such as date(), and with date format from the input string.

I already tried to use this code below and it just returned the format string:

$string = preg_replace('/\{POST_DATE,(.*)\}/',date('$1'),$template);

and I got the return string here:

TEXT TEXT TEXT m/d/Y TEXT TEXT TEXT

I am not sure where I was wrong and if there are many {POST_DATE,m/d/Y} string in text, so how can I replace all of them following the way above.

The date function is being passed a literal value of '$1'. The preg_replace function knows to interpret that as being the value of the captured subpattern, but the date function doesn't.

You can use the "e" modifier in preg_replace to pass $1 to your function:

preg_replace('/\{POST_DATE,(.*?)\}/e','date("$1")',$input);

Note I've also made the .* non-greedy by adding a ? character after it, as you'd capture more than you intend if there was a second } character in the input string.

To test this, try the following:

$s = "TEXT TEXT TEXT {POST_DATE,m/d/y} TEXT TEXT TEXT";
print preg_replace('/\{POST_DATE,(.*?)\}/e','date("$1")',$s);

Output is:

TEXT TEXT TEXT 12/19/12 TEXT TEXT TEXT

And to avoid deprecated code, you're better off using preg_replace_callback, though it's not as elegant:

$s = "TEXT TEXT TEXT {POST_DATE,m/d/y} TEXT TEXT TEXT";
print preg_replace_callback('/\{POST_DATE,(.*?)\}/',
                            create_function('$matches',
                                            'return date($matches[1]);'),
                            $s);

(which gives the same output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM