好的,我有一个字符串 $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 = ".*(\d+\.\d+.\d+).*";
但我无法让它按照我需要的方式工作。总而言之,我需要在字符串中找到日期,将其从字符串中删除并正确格式化。干杯。
将日期与正则表达式匹配可能非常复杂。看这个问题 https://stackoverflow.com/questions/5978510/regex-to-match-date举个正则表达式的例子。找到日期后,您可以使用以下命令将其从标题中删除字符串替换() http://php.net/manual/en/function.str-replace.php.
这是一个基本的实现:
$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.";
}
Output:
20.08.12 First Test Event => First Test Event, 20.08.2012
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)