Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

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

like image 387
udexter Avatar asked Dec 02 '22 03:12

udexter


1 Answers

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.

like image 114
Delan Azabani Avatar answered Jan 17 '23 12:01

Delan Azabani