I need some help with a regular expressions. I'm trying to validate if a string looks like 'yyyy-mm-dd', this is my code so far:
case "date":
if (preg_match("/^[0-9\-]/i",$value)){
$date = explode("-",$value);
$year = $date[0];
$month = $date[1];
$day = $date[2];
if (!checkdate($month,$day,$year))
{
$this->errors[] = "Ogiltigt datum.";
}
} else {
$this->errors[] = "Ogiltigt datum angivet.";
}
break;
I am very new to regular expressions, thanks.
You can use this:
if ( preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}\z/', $value) ) { ...
however this kind of pattern can validate something like 0000-40-99
pattern details:
/ # pattern delimiter
^ # anchor: start of the string
[0-9]{4} # four digits
- # literal: -
[0-9]{2}
-
[0-9]{2}
\z # anchor: end of the string
/ # pattern delimiter
Using capturing group, you don't need call explode.
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value, $matches)) {
$year = $matches[1];
$month = $matches[2];
$day = $matches[3];
...
}
\d matches any digit characters.{n} is quantifier: to match previous pattern exactly 4 times.$matches[1], $matches[2], ...
$matches[0] contains entire matched string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With