搜索并用多个随机值替换一些值

Search and replace some value with multiple random values

我有一个包含以下内容的文件。

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

我需要用一些随机日期替换#date#,这些随机日期是我通过使用以下代码为每个#date# 生成新的随机值生成的。

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

目前所有日期都被替换为相同的值。 谢谢。

您可以使用 preg_replace_callback 每次替换时生成一个新的随机日期:

$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);

输出:

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

Demo on 3v4l.org