?
Solved

PHP checking if string matches pattern

Posted on 2013-06-07
3
Medium Priority
?
521 Views
Last Modified: 2013-06-07
Hello,

I would like to check if a string matches this pattern:

'yyyy-mm-dd hh:mm'

I am not sure how to do this will PHP.

Thanks in advance for any advice.

Cheers,
0
Comment
Question by:1Cougar
  • 2
3 Comments
 
LVL 60

Accepted Solution

by:
Julian Hansen earned 2000 total points
ID: 39228504
You can use a regular expression

preg_match('/[0-9{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}/', $string);

Will return 0 if no match or > 0 if a match.
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 39228514
Assumes 0 padded fields for month, day, hour and minute.

If you want to validate actual month / day values better to do that in code - working out leap years and different month values might be overly complex.

You can do this by modifying your preg_match call to

<?php
// RegEx pattern with () to save matched components into $matches array
$pattern = '/([0-9]{4})\-([0-9]{2})\-([0-9]{2}) ([0-9]{2}):([0-9]{2})/';
$string = '2012-11-21 12:45';
echo preg_match($pattern, $string, $matches);
echo "<pre>";
// $matches now holds yyyy, mm, dd, hh, mm in array values 1-5
print_r($matches);
echo "</pre>";
?>

Open in new window

0
 

Author Comment

by:1Cougar
ID: 39228578
Hi,

Thank you!  Your first answer works fine--all dates are 0 padded.

Many thanks for your help!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses
Course of the Month15 days, 7 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question