2

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

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

4

3 回答 3

4

使用正则表达式匹配日期可能非常复杂。有关示例正则表达式,请参阅此问题。找到日期后,您可以使用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
于 2012-08-19T10:07:22.043 回答
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;
于 2012-08-19T10:23:50.810 回答
0

I made some tests and this should be ok the new_title() does a replace of / by . then the preg_split splits the string when the date is met

<?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];
}

hope this could help

regards

于 2012-08-19T10:24:23.197 回答