【问题标题】:Search and replace some value with multiple random values搜索并用多个随机值替换某个值
【发布时间】:2019-06-14 00:39:02
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 当然,你需要它识别文本文件中的所有日期,遍历它们并一一替换。

标签: php arrays string replace str-replace


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-06
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多