I'd like some help please. I'm having am input field where I'd like to check if the user has entered his date of birth in these formats: dd/mm/yyyy
or dd-mm-yyyy
if(preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/', $_POST['dob'])){
// ok
} else {
// there's an error
}
How can I change my regular expression to match either the '/'
or '-'
between the numbers?
Put the patterns which matches date formats inside a non-capturing group delimited by an alternation operator.
if(preg_match('~^[0-9]{2}(?:-[0-9]{2}-[0-9]{4}|/[0-9]{2}/[0-9]{4})$~', $_POST['dob'])){
// ok
} else {
// there's an error
}
OR
Use capturing group and then refer the capturing characters through back-referencing.
if(preg_match('~^[0-9]{2}([-/])[0-9]{2}\1[0-9]{4}$~', $_POST['dob'])){
// ok
} else {
// there's an error
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.