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

时间:2012-08-19 09:38:49

标签: php regex

好的,所以我有一个字符串$ 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+).*";

但是我无法以我需要的方式工作。总而言之,我需要在字符串中找到日期,将其从字符串中删除并正确格式化。欢呼声。

3 个答案:

答案 0 :(得分:3)

使用正则表达式匹配日期可能非常复杂。有关示例正则表达式,请参阅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

答案 1 :(得分:0)

<?php
#$title_string = "20.08.12 First Test Event";
#$title_string = "First Test event 20/08/12";
$title_string = "First Test 20.08.2012 Event";

preg_match('~([0-9]{1,2}[\.|/][0-9]{1,2}[\.|/][0-9]{1,4})~', $title_string, $matches);
$date = $matches[1];
$title = preg_replace('~[[:space:]]{2,}~', ' ', str_replace($date, '', $title_string));

echo 'Date: '.$date.'<br />';
echo 'Title: '.$title;

答案 2 :(得分:0)

我做了一些测试,这应该没问题 new_title()替换/ by。然后preg_split在满足日期时拆分字符串

<?php 
$regex = "#(\d+[./]\d+[./]\d+)#";
print $regex . "\n\n";

print "20.08.12 First Test Event";
$title_string = new_string("20.08.12 First Test Event");
print $title_string . "\n";
$var = preg_split($regex,$title_string,-1,PREG_SPLIT_DELIM_CAPTURE);
print "result";
var_dump($var);

print "\n\n";

print "First Test event 20/08/12\n";
$title_string = new_string("First Test event 20/08/12");
print $title_string . "\n";
$var = preg_split($regex,$title_string,-1,PREG_SPLIT_DELIM_CAPTURE);
print "result";
var_dump($var);

print "\n\n";

$title_string = new_string("First Test 20.08.2012 Event");
print $title_string . "\n";
$var = preg_split($regex,$title_string,-1,PREG_SPLIT_DELIM_CAPTURE);
print "result";
var_dump($var);

function new_string($string) {
    return preg_replace_callback( "#(\d+)[./](\d+)[./](\d+)#",
            "new_date",
            $string);
}

function new_date($matches) {
  return $matches[1].'.'.$matches[2].'.'.$matches[3];
}
希望这可以帮助

问候