PHP:如何将字符串中任意日期动态替换为当前日期
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_replacewill replace all of them with the current date. - Using
date('m/Y')ensures the replacement date uses the sameMM/YYYYformat as the dates we're matching. If you need a different format (likeYYYY-MM), just adjust the argument todate()(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

