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:
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:
Output is:
And to avoid deprecated code, you’re better off using preg_replace_callback, though it’s not as elegant:
(which gives the same output)