Unknown modifier '(' when using preg_match() with a REGEX expression [duplicate]
Asked Answered
M

5

4

I'm trying to validate dates like DD/MM/YYYY with PHP using preg_match(). This is what my REGEX expression looks like:

$pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";

But using it with a correct value, I get this message:

preg_match(): Unknown modifier '('

Complete code:

    $pattern = "/^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$/";
    $date = "01/03/2011";

    if(preg_match($pattern, $date)) return TRUE;

Thank you in advance

Melisa answered 1/3, 2011 at 10:31 Comment(0)
T
13

Escape the / characters inside the expression as \/.

$pattern = "/^([123]0|[012][1-9]|31)\/(0[1-9]|1[012])\/(19[0-9]{2}|2[0-9]{3})$/";

As other answers have noted, it looks better to use another delimiter that isn't used in the expression, such as ~ to avoid the 'leaning toothpicks' effect that makes it harder to read.

Thiel answered 1/3, 2011 at 10:33 Comment(0)
D
3

You use / as delimiter and also in your expression. Now

/^([123]0|[012][1-9]|31)/

Is the "complete" expression and all following is expected as modifier, also the (.

You can simply use another delimiter.

~^([123]0|[012][1-9]|31)/(0[1-9]|1[012])/(19[0-9]{2}|2[0-9]{3})$~

Or you escape all occurence of / within the expression, but I would prefer another delimiter ;) Its more readable.

Directed answered 1/3, 2011 at 10:36 Comment(0)
D
2

your delimiter is /, but you are using it inside the pattern itself. Use a different delimiter, or escape the /

Dermatoid answered 1/3, 2011 at 10:35 Comment(0)
A
1

You could escape the slashes / as suggested. It'll eventually lead to the Leaning Toothpick Syndome, though.

It's common to use different delimiters to keep your regular expression clean:

// Using "=" as delimiter
preg_match('=^ ... / ... $=', $input);
Auditorium answered 1/3, 2011 at 10:35 Comment(0)
H
0

checek date using below function

 function checkDateFormat($date)
    {
      //match the format of the date
      if (preg_match ("/^([0-9]{2}) \/([0-9]{2})\/([0-9]{4})$/", $date, $parts))
      {
        //check weather the date is valid of not
        if(checkdate($parts[2],$parts[1],$parts[3]))
          return true;
        else
         return false;
      }
      else
        return false;
    }

echo checkDateFormat("29/02/2008"); //return true
echo checkDateFormat("29/02/2007"); //return false
Haemocyte answered 1/3, 2011 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.