3

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.

2
  • Thanks @mario. I just edited my question for more clear. Commented Dec 19, 2012 at 8:20
  • @mario Please, don't advise using the /e modifier, this has been DEPRECATED as of PHP 5.5 Commented Dec 19, 2012 at 8:22

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Watch out, PHP 5.5 is deprecating the e modifier in favor of preg_replace_callback. Switch now to save the annoyance factor later.
You may consider adding an exemple using closures (As of PHP >=5.3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.