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

时间:2019-01-20 11:52:54

标签: php arrays string replace str-replace

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

  

一些文字bla-bla#date#其他文字#date#其他#date#

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

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

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

1 个答案:

答案 0 :(得分:3)

每次替换preg_replace_callback时,您都可以使用Demo on 3v4l.org生成一个新的随机日期:

$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

(?<!\\)(?:\\.)*\((?:\\.|[^:)\\])*:(?:\\.|[^:)\\])*\)