Solved

PHP checking if string matches pattern

Posted on 2013-06-07
3
495 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 51

Accepted Solution

by:
Julian Hansen earned 500 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 51

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now