You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:如何将字符串中任意日期动态替换为当前日期

Solution: Dynamically Replace Any MM/YYYY Date with Current Date

Hey there! The issue with using str_replace here is that it only targets exact string matches—so it can't handle arbitrary dates like 03/2020 or 09/2023 unless you hardcode each one. Instead, we can use regular expressions with PHP's preg_replace function to detect any date in the MM/YYYY format and replace it with the current date.

Step 1: Use a Regular Expression to Match Dates

The regex pattern /\d{2}\/\d{4}/ will match any string that follows the "two digits / four digits" format (e.g., 12/2017, 05/2024):

  • \d{2}: Matches exactly 2 digits (for the month)
  • \/: Escapes the forward slash (since it's a special character in regex)
  • \d{4}: Matches exactly 4 digits (for the year)

Step 2: Updated PHP Code

Here's the modified code that dynamically replaces all matching dates with the current date (formatted as MM/YYYY to match the original pattern):

<?php
$string = 'we will be held the event in 12/2017 . and waiting for your ..';
// Replace any MM/YYYY date with current date in same format
$updatedString = preg_replace('/\d{2}\/\d{4}/', date('m/Y'), $string);
?>

Step 3: Integrate with Your HTML

To display the updated text in your HTML structure, output the processed string inside the <p> tag:

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <div class="panel panel-default">
        <div class="panel-body">
          <p><?php echo $updatedString; ?></p>
        </div>
      </div>
    </div>
  </div>
</div>

How It Works

  • If your original string has multiple dates (e.g., we have events in 01/2023 and 06/2024), preg_replace will replace all of them with the current date.
  • Using date('m/Y') ensures the replacement date uses the same MM/YYYY format as the dates we're matching. If you need a different format (like YYYY-MM), just adjust the argument to date() (e.g., date('Y-m')).

Bonus: Matching Other Date Formats

If you need to handle other formats (like DD/MM/YYYY), update the regex pattern:

  • For DD/MM/YYYY: Use /\d{2}\/\d{2}\/\d{4}/
  • For YYYY/MM: Use /\d{4}\/\d{2}/

Just make sure to adjust the date() format to match the replacement you want!

内容的提问来源于stack exchange,提问作者designer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:14:07