Link to home
Create AccountLog in
Avatar of 1Cougar
1Cougar

asked on

PHP checking if string matches pattern

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,
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
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

Avatar of 1Cougar
1Cougar

ASKER

Hi,

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

Many thanks for your help!