使用正则表达式从字符串中删除日期 [英] Remove date from string with regular expressions

查看:31
本文介绍了使用正则表达式从字符串中删除日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, so I have a string $title_string which could look like any of the following:

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

我需要以两个变量结束:

I need to end up with two variables:

$title = "First Test Event";
$date = "20.08.12";

日期的格式应该转换为句号,无论它最初是什么.

The formatting for the date should be converted to full-stops, regardless of what it was originally.

我开始使用的正则表达式字符串如下所示:

The Regex string that I started with looks something like this:

$regex = ".*(\d+\.\d+.\d+).*";

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

But I can't get this to work in the way I need it to. So all in all, I need to locate a date in a string, remove it from the string and format it correctly. Cheers.

推荐答案

用正则表达式匹配日期可能非常复杂.有关正则表达式示例,请参阅此问题.找到日期后,您可以使用 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

这篇关于使用正则表达式从字符串中删除日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆