Page 1 of 1

Preg_match not matching date format

Posted: Sat Feb 26, 2011 10:53 pm
by cbwd
Hi,

I've not posted on here before, but have used the forum as a resource in the past. Usually I like to figure things out for myself but this one has me confused.

I have a fair amount of experience with php but up until now have not needed to use regex (I did use it with Perl around 2000/1 but have forgotten everything).

Anyway the issue is, I have a date format '2011-12-31' which I believe should match the pattern below - problem is it doesn't!

Does anyone have any ideas?

Code: Select all

if (preg_match('((19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))',$date_from)) {
            $valid_input = 1;
            echo "<p>Date From is valid</p>";
}  else {
            echo '<p class="red_text">Date From is invalid.</p>';
            $valid_input = 0;
}

Re: Preg_match not matching date format

Posted: Sat Feb 26, 2011 11:04 pm
by Weirdan
preg_match needs pattern separators, like this (slash being a separator): preg_match('/something/', ...)

Re: Preg_match not matching date format

Posted: Sun Feb 27, 2011 1:37 am
by cbwd
Brilliant! Thanks for that, this did the trick (also added the ^ and $ to prevent any text being entered before/after the date):

Code: Select all

preg_match('/^((19|20)\d\d[-](0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01]))$/',$date_from)

Re: Preg_match not matching date format

Posted: Sun Feb 27, 2011 3:02 am
by pickle
If you're trying to validate a date, this won't work - I could run "2011-02-31" and it would match.

Your best bet is to extract the year, month & day, and throw it at checkdate().

Re: Preg_match not matching date format

Posted: Mon Feb 28, 2011 11:21 am
by ridgerunner
Actually, I just ran your original code snippet and it works just fine (it is perfectly valid to use parentheses for the regex delimiter). And there is nothing wrong with the regex. The only critique I have is that you use a character class with just one character in it (i.e. '[-]'). In this case, you can simply use '-'. However, both syntaxes are equally valid with regard to matching.