Jump to content

Help with Regular Expressions


ladieballer2004

Recommended Posts

I have a preg_match and it is supposed to flag if my date isn't in MM-YYYY format.  Here is my code

if 
  (!empty($_POST['StartDate'][$row]) && !preg_match('/^(0[1-9]|1[0-2]) [-] (19|20)\d{2}$/',$_POST['Startdate'][$row]))
  {echo '<b>One of your Start Date columns is not in the proper format. Make Sure it is MM-YYYY<br/>';$dataOK=FALSE;}

 

what did i do wrong? Please Help

Link to comment
https://forums.phpfreaks.com/topic/171921-help-with-regular-expressions/
Share on other sites

@ ladieballer,

 

Looking at your preg pattern, notice you have a space between your first alternation and your second.. so the format looks for MM - YYYY. You are also using captures.. not sure if you need them or not.. given that it is a format you are looking for, I would resort to using non capturing groups instead. Finally, that lone hyphen in the middle doesn't need to be in a character class [].. You can simply have it sitting there on its own. So that pattern could be as such:

 

/^(?:0[1-9]|1[0-2])-(?:19|20)\d{2}$/

 

@ILMV,

 

Your pattern could match 00-0000 for instance... There's no need for adding the question mark after your intervals ({2} and {4}). Besides the capturing issue, that hyphen doesn't need to be escaped.. as mentioned, it can simply sit there and it will be treated as a literal.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.