更新时间:2023-02-18 15:19:21
用正则表达式匹配日期可能非常复杂.有关正则表达式示例,请参阅此问题.找到日期后,您可以使用 str_replace().
Matching dates with regular expressions can be quite complex. See this question for an example regex. Once you've found the date, you can remove it from the title using str_replace().
这是一个基本的实现:
$title_string = "20.08.12 First Test Event";
if ( preg_match('@(?:\s+|^)((\d{1,2})([./])(\d{1,2})\3(\d{2}|\d{4}))(?:\s+|$)@', $title_string, $matches) ) {
//Convert 2-digits years to 4-digit years.
$year = intval($matches[5]);
if ($year < 30) { //Arbitrary cutoff = 2030.
$year = 2000 + $year;
} else if ($year < 100) {
$year = 1900 + $year;
}
$date = $matches[2] . '.' . $matches[4] . '.' . $year;
$title = trim(str_replace($matches[0], ' ', $title_string));
echo $title_string, ' => ', $title, ', ', $date;
} else {
echo "Failed to parse the title.";
}
输出:
20.08.12 First Test Event => First Test Event, 20.08.2012