• Status: Solved
  • Priority: High
  • Security: Public
  • Views: 85
  • Last Modified:

PHP Sanitizing Date Inputs via REGEX for first instance of d/m/Y

Basically, I want to return the matching FIRST pattern of 1 or 2 digits (as the day), 1 or 2 (digits as the month), 4 digits as the year separated by forwarding slash characters '/' from a valid or malformed input.

given these hypothetical inputs:

01/01/2017
1/1/2017/01/03/2017
1/1/2017/01/03/2017/a/b/z/0000
a/1/2/b/c/9/1/g/8/99/1/34/9/99/2017/z
ab/cd/efgh

I would like the output to be:
01/01/2017
1/1/2017
1/1/2017
9/99/2017
FALSE
0
NerdsOfTech
Asked:
NerdsOfTech
2 Solutions
 
Bill PrewCommented:
Try this REGEX pattern:

[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}

Open in new window


»bp
0
 
Dan CraciunIT ConsultantCommented:
You could filter out the 9/99 date from regex:

if (preg_match('%[0-3]?[0-9]/[0-1]?[0-9]/[1-2][0-9]{3}%', $subject, $regs)) {
	$result = $regs[0];
} else {
	$result = "";
}

Open in new window


HTH,
Dan
0
 
NerdsOfTechTechnology ScientistAuthor Commented:
[code]([0-2]?[0-9]|3[0-1])/([0]?[0-9]|1[0-2])/[1-2][0-9]{3}[/code] would be a step closer to valid dates but 99/99/9999 is ok as an input for this question. The extraction is ran through another function checkdate() to process the final validation. Thanks Dan for the extra $result = $regs[0]; line as this gives FIRST occurance. Thanks Bill for the first valid REGEX to match. I'll split points to both.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now