0

I want to replace variables in text so that a user can set a custom date format.

In the simplest example, they can do this....

$text = 'The date today is {{current_date|Y-m-d}} isnt it';

$text = preg_replace('/{{current_date\|(.*)}}/', date("$1"), $text);

echo $text;

But this returns...

The date today is Y-m-d isnt it

But I want it to return....

The date today is 2020-07-10 isnt it

So the date is not being formatted. Any ideas what I'm doing wrong?

2 Answers 2

1

The captured date format won't be passed into the date function. It will only be available for interpolation into the replacament string. You'll want to use preg_replace_callback instead:

$text = preg_replace_callback('/{{current_date\|(.*)}}/', function($match) {
    return date($match[1]); 
}, $text);

This allows you to pass the captured string into a function for further processing.

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

2 Comments

You might want to do some sanitization/validation of the time format, if it's indeed user input. For example, by limiting the .* to only [a-zA-Z/_-]+ characters, and especially not allowing the backslash. Because one could, for example, do something like... $xss = "\<\s\c\\r\i\p\\t\>\a\l\\e\\r\\t\(\'\!\'\)\;\<\/\s\c\\r\i\p\\t\>"; echo date($xss);. o_O
Thanks, yep I sanitise all user input, I just simplified the example in the question.
0

If it is PHP version <=5.6, the below code will work. Later version /e is depricated

$text = 'The date today is {{current_date|Y-m-d}} isnt it';
$text = preg_replace('/{{current_date\|(.*)}}/e', 'date("$1")', $text);
echo $text;

1 Comment

It was deprecated for good reason, and must be used with caution equal to anything you might pass into eval. From the manual: "Caution: Use of this modifier is discouraged, as it can easily introduce remote code execution vulnerabilities. To prevent these, the preg_replace_callback() function should be used instead." Also, PHP 5.6 became EOL in end of 2018, incl. no new security fixes, and as such should no longer be deployed. php.net/eol.php

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.