views:

19

answers:

2

Hi guys.. I have been working on my date regular expression all day... I want a date format to be YYYY-MM-DD.

$date_regex ='^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$';

if (preg_match($date_regex, $dateString)) {
        echo "good format";
    }

keeps giving me error

preg_match() [function.preg-match]: No ending delimiter '^' found in test.php on line 19

Anyone help?? Thanks a lot!!

+1  A: 

You need to wrap your regular expression in a pair of delimiting characters. Also, you need to escape the dashes in your character classes using \.

Try this (I'm using # as a delimiter):

$date_regex ='#^(19|20)\d\d[\- /.](0[1-9]|1[012])[\- /.](0[1-9]|[12][0-9]|3[01])$#';
BoltClock
Thanks.......A LOT!!!!!!!!!!!
I need to wait for 8 min. to give u accepted answer
I updated my answer a tiny bit by the way. Use the updated answer to make sure `-` is matched properly.
BoltClock
IC. Thanks a lot.
+1  A: 

You need to include the /s otherwise the regex thinks you are limiting it with the ^

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

Regards

Graeme Smyth
AAh BoltClock beat me to it, and gave a better answer to boot :p
Graeme Smyth
If you use `/` you need to escape the other `/`s in the regex so PHP doesn't end the regex prematurely. Specifically in the character classes (escape the dash too): [\- \/.]
BoltClock
also tried to bold the relevant /s but the code bit didnt pick them up :s
Graeme Smyth
You can't format text in code blocks :)
BoltClock
Yep same in Perl, very used to writing \/ in Regexes,
Graeme Smyth