clarkk clarkk - 3 months ago 9
PHP Question

regexp - match multiple variations of datestamp

I need to match multiple variations of a datestamp

$test = array(
'01-05-2011',
'01-05-11',
'01.12.2012',
'30042016'
);

$date_day_pattern = '01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31';
$date_year_pattern = '(?:20)?10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30';

$date_pattern = "(?<!\d)($date_day_pattern)[^\d\n]?($date_day_pattern)[^\d\n]?($date_year_pattern)(?!\d)";
foreach($test as $input){
preg_match("/$date_pattern/", $input, $matches);
print_r($matches);
}


http://www.tehplayground.com/#R1sjJxFho

Answer

This shortened regex should work for your examples:

$test = array(
    '01-05-2011',
    '01-05-11',
    '01.12.2012',
    '30042016'
);

$date_pattern =
   '/\b(0[1-9]|[12][0-9]|3[01])([.-]?)(0[1-9]|1[0-2])\2((?:20)?(?:[12][0-9]|30))\b/';

foreach($test as $input){
   echo $input."\n";
   preg_match($date_pattern, $input, $matches); print_r($matches);
}

Though you should consider using date parsing functions such as strtotime for proper date validations and parsing.

Output:

01-05-2011
Array
(
    [0] => 01-05-2011
    [1] => 01
    [2] => 05
    [3] => 2011
)
01-05-11
Array
(
    [0] => 01-05-11
    [1] => 01
    [2] => 05
    [3] => 11
)
01.12.2012
Array
(
    [0] => 01.12.2012
    [1] => 01
    [2] => 12
    [3] => 2012
)
30042016
Array
(
    [0] => 30042016
    [1] => 30
    [2] => 04
    [3] => 2016
)
Comments