gpt4 book ai didi

php - 使用正则表达式从字符串中删除日期

转载 作者:行者123 更新时间:2023-12-04 18:14:16 26 4
gpt4 key购买 nike

好的,所以我有一个字符串 $title_string ,它可能看起来像以下任何一种:

$title_string = "20.08.12 First Test Event";
$title_string = "First Test event 20/08/12";
$title_string = "First Test 20.08.2012 Event";

我需要以两个变量结束:
$title = "First Test Event";
$date = "20.08.12";

无论最初是什么,日期的格式都应转换为句号。

我开始使用的 Regex 字符串看起来像这样:
$regex = ".*(\d+\.\d+.\d+).*";

但我不能让它以我需要的方式工作。所以总而言之,我需要在字符串中找到一个日期,将其从字符串中删除并正确格式化。干杯。

最佳答案

使用正则表达式匹配日期可能非常复杂。见 this question例如正则表达式。找到日期后,您可以使用 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

关于php - 使用正则表达式从字符串中删除日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12025546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com