Search code examples
phppreg-match

PHP preg_match combined with checkdat


I have this piece of code in the middle of my web application.

  if (preg_match ("/^[-0-9]/", $strDate) == TRUE)
  {
      $dateParts = explode("-", $strDate);
      if (count($dateParts) === 3)
      {
          try
          {
              if (checkdate($dateParts[0], $dateParts[1], $dateParts[2]) === TRUE)
              {
                  return TRUE;
              }
          }
          catch (Exception $e)
          {
              //purposely blank for now.
          }
      }
  }

I haven't included any surrounding code because it's a fairly lengthy app. To start, the $strDate variable I know exactly what is held in there. I can echo it out right before the if statement begins. If $strDate is a valid date or any combination of 'TBD' the statement validates as expected. The problem comes when an invalid date enters the function.

For instance,

$strDate = '03-01-2017asdf';

With this input I would expect the preg_match to catch it and kick it out of the if statement. Instead it runs the try-except and php throws a non formed number error. Any ideas what I am doing wrong here? I'm sure it has to do with my preg_match statement.


Solution

  • Change your regular expression to require a match until the end of the input string:

    /^[-0-9]+$/
    

    So add the + to say you can have multiple digits and hyphens, and then the $ to say that the previous pattern must match until the end of the string, so nothing else can be added like in your example. Of course, you could look for more complex regular expressions that check for valid parts of the date, the number of hyphens, ... etc, which can become quite complex, as you can see in this answer.