Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match yyyy-mm-dd

Tags:

regex

php


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.

like image 868
Petter Pettersson Avatar asked Jan 22 '26 09:01

Petter Pettersson


2 Answers

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
like image 64
Casimir et Hippolyte Avatar answered Jan 23 '26 21:01

Casimir et Hippolyte


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.
  • You can access the matched group using $matches[1], $matches[2], ...
    • $matches[0] contains entire matched string.
like image 39
falsetru Avatar answered Jan 23 '26 22:01

falsetru