0

I have a file with the following content.

Some text bla-bla #date# other text #date# some other #date#

I need to replace #date# with some random date which I generate by using the following code with new random value for each #date#.

date('Y-m-d', strtotime( '+'.mt_rand(0,45).' days'))

At the moment all dates are replaced with the same value. Tks.

1
  • 1
    Sure, you need it identify all dates in the text file, iterate over them and replace them one by one. Commented Jan 20, 2019 at 11:57

1 Answer 1

3

You can use preg_replace_callback to generate a new random date each time it replaces:

$string = 'Some text bla-bla #date# other text #date# some other #date#';
echo preg_replace_callback('/#date#/', function () { return date('Y-m-d', strtotime( '+'.mt_rand(0,45).' days')); }, $string);

Output:

Some text bla-bla 2019-01-22 other text 2019-02-16 some other 2019-02-19

Demo on 3v4l.org

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

Comments

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.