Preg_match not matching date format

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
cbwd
Forum Newbie
Posts: 2
Joined: Sat Feb 26, 2011 10:26 pm
Location: New Zealand

Preg_match not matching date format

Post 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;
}
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Preg_match not matching date format

Post by Weirdan »

preg_match needs pattern separators, like this (slash being a separator): preg_match('/something/', ...)
cbwd
Forum Newbie
Posts: 2
Joined: Sat Feb 26, 2011 10:26 pm
Location: New Zealand

Re: Preg_match not matching date format

Post 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)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Preg_match not matching date format

Post 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().
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Preg_match not matching date format

Post 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.
Post Reply