?
Solved

PHP checking if string matches pattern

Posted on 2013-06-07
3
Medium Priority
?
515 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 58

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 58

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

800 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