dadamssg Posted June 22, 2012 Share Posted June 22, 2012 I found this preg_match() function which searches the parts of a string and uses the checkdate() function to see if it is a date. It expects the format of the date to be "YYYY-MM-DD". I would like to rewrite it to expect the format to be "MM/DD/YYYY". <?php function checkDateFormat($date) { //match the format of the date if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) { //check weather the date is valid of not if(checkdate($parts[2],$parts[3],$parts[1])) return true; else return false; } else return false; } I'm pretty sure the following is write to change the string length of each part but i don't know how to change the expected "-"'s to be a "/"'s. <?php if (preg_match ("/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/", $date, $parts)) Any help would be greatly appreciated! Quote Link to comment Share on other sites More sharing options...
JAY6390 Posted June 22, 2012 Share Posted June 22, 2012 Just change the two / to be ~ and then change the two )-( to read )/( Quote Link to comment Share on other sites More sharing options...
dadamssg Posted June 22, 2012 Author Share Posted June 22, 2012 perfect. thanks! Quote Link to comment Share on other sites More sharing options...
.josh Posted June 23, 2012 Share Posted June 23, 2012 to clarify, the function expects a delimiter for the pattern, a designated character at the start and end of the pattern. This is because modifiers are also placed inside the string (after the ending delimiter). You can use most any non-alphanumeric character as the delimiter, but whatever you choose has to be escaped if you want to use it in the actual pattern. So for example, in your OP you have / as the delimiter, but wanted to use that character in your pattern. So you could have kept / as the delimiter and just escaped the / in your pattern by doing \/ I personally like using ~ because it rarely comes up in patterns and I hate escaping. But just sayin'... Also, I would also like to point out that you don't actually need to use regex for this..you can explode at the /, count the elements exploded (to make sure there are only 3) and then put them in that checkdate. Quote Link to comment Share on other sites More sharing options...
The Little Guy Posted June 26, 2012 Share Posted June 26, 2012 Another option: <?php function checkDateFormat($date){ @list($m, $d, $y) = explode("/", $date); if(empty($m) || empty($d) || empty($y) || !checkdate($m, $d, $y)) return false; return true; } var_dump(checkDateFormat("13/2012")); var_dump(checkDateFormat("cat")); var_dump(checkDateFormat("2012-05-05")); var_dump(checkDateFormat("2012/05/05")); var_dump(checkDateFormat("12/05/1205")); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.