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
LVL 22
NerdsOfTechTechnology ScientistAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Regular Expressions

From novice to tech pro — start learning today.