Reputation: 33901
I'm using the following regex to parse a date in dd/mm/yyyy
format:
^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$
I've checked it on strfriend and it all looks ok. However, when testing for it in PHP with preg_match
it doesn't recognize it:
if(!preg_match("/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/",trim($_POST['dob']))){
$error .= "You must enter a valid date of birth.";
}
This happens with input such as 29/10/1987
and 01-01-2001
, and I'm not sure why it doesn't work!
I also get the following warning:
Warning: preg_match() [function.preg-match]: Unknown modifier '.' in /home/queensba/public_html/workers/apply.php on line 18
which I'm not sure how to interpret.
Upvotes: 1
Views: 148
Reputation: 26139
Don't use double quotes for strings, they're for templates. If you have '/' in your pattern, you cannot begin and end it with the same character, do it with "%","#" or any other characters... If you have unicode string, you have to use the "u" flag.
Upvotes: 1
Reputation: 4711
If you use '/' in within your regex, you may not start/end the regular expression with it. Just replace it with '#' for example.
if(!preg_match("#^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$#",trim($_POST['dob']))){
$error .= "You must enter a valid date of birth.";
}
(BTW, Modifiers would come after the final delimiter '#'. So the warning appeared because PHP thought the regex would end after the second '/'.)
Upvotes: 4
Reputation: 32532
Since you are using /.../ as the pattern delimiter you need to escape all other instances of / like \/ alternative is to use a different delimiter like ~
Upvotes: 1
Reputation: 336158
The /
inside your regex trip up PHP because it thinks they are your regex delimiters.
Try
if(!preg_match("#^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$#",trim($_POST['dob']))){
$error .= "You must enter a valid date of birth.";
}
Upvotes: 2