开发者

Regex validate dates like "Sun, 20 Jun 10"

I'm working on a regular expression that will only return true when a date string is in a format something like 'ddd, dd mmm yy'.

Valid matches would be values like "Sun, 20 Jun 10" or "Mon, 21 Jun 10" but not "Sunday, 20 Jun 10" or "20 Jun 10".

This will be used with mb_ereg in PHP.

My attempts so far h开发者_JAVA技巧ave only got me half way there. Any help appreciated!

Thanks, Dave


"/[a-z]{3}, \\d{2} [a-z]{3} \\d{2}/i"

If i flag (case insensitive) is not supported, replace [a-z] with [a-zA-Z]

Also, replace [a-z]{3} with (Sun|Mon|Tue|Wed|Thu|Fri|Sat) and corresponding (Month|List) for a stricter validation.


This is one solution. Days like "00" are not allowed.

$date = 'Fri, 18 Jun 10';
$regex = '#([A-Za-z]{3}), ((?:0[1-9])|(?:(?:1|2)[0-9])|(?:3(?:0|1))) ([A-Za-z]{3}) ([0-9]{2})#';
preg_match($regex, $date, $matches);

// Create Vars out of the matching...
$day_abbr = $matches[1];
$day = $matches[2];
$month_abbr = $matches[3];
$year = $matches[4];

If you want to allow days without leading zeros you will have to use this regex (just added an questionmark. This means dates like "Sun, 8 Jun 10" are also valid with the following regex.

$regex = '#([A-Za-z]{3}), ((?:0?[1-9])|(?:(?:1|2)[0-9])|(?:3(?:0|1))) ([A-Za-z]{3}) ([0-9]{2})#';


I'm not sure why you'd prefer ereg over preg, but here:

$regex = '([A-Z][a-z]{2}), (([012][0-9])|(3[01])|[0-9]) ([A-Z][a-z]{2}) ([0-9]{2})';
mb_ereg($regex, "Sun, 31 Jun 10", $regs);

Of course, if you want to convert to a POSIX time, you'd need to map the month part to an integer and use mktime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜