Contao\Date::getRegexp PHP Method

getRegexp() public static method

Return a regular expression to check a date
public static getRegexp ( string $strFormat = null ) : string
$strFormat string An optional format string
return string The regular expression string
    public static function getRegexp($strFormat = null)
    {
        if ($strFormat === null) {
            $strFormat = static::getNumericDateFormat();
        }
        if (!static::isNumericFormat($strFormat)) {
            throw new \Exception(sprintf('Invalid date format "%s"', $strFormat));
        }
        return preg_replace_callback('/[a-zA-Z]/', function ($matches) {
            // Thanks to Christian Labuda
            $arrRegexp = array('a' => '(?P<a>am|pm)', 'A' => '(?P<A>AM|PM)', 'd' => '(?P<d>0[1-9]|[12][0-9]|3[01])', 'g' => '(?P<g>[1-9]|1[0-2])', 'G' => '(?P<G>[0-9]|1[0-9]|2[0-3])', 'h' => '(?P<h>0[1-9]|1[0-2])', 'H' => '(?P<H>[01][0-9]|2[0-3])', 'i' => '(?P<i>[0-5][0-9])', 'j' => '(?P<j>[1-9]|[12][0-9]|3[01])', 'm' => '(?P<m>0[1-9]|1[0-2])', 'n' => '(?P<n>[1-9]|1[0-2])', 's' => '(?P<s>[0-5][0-9])', 'Y' => '(?P<Y>[0-9]{4})', 'y' => '(?P<y>[0-9]{2})');
            return isset($arrRegexp[$matches[0]]) ? $arrRegexp[$matches[0]] : $matches[0];
        }, preg_quote($strFormat));
    }

Usage Example

 /**
  * Process a custom date regexp on a widget.
  *
  * @param string $rgxp   The rgxp being evaluated.
  *
  * @param string $value  The value to check.
  *
  * @param Widget $widget The widget to process.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 public static function processCustomDateRegexp($rgxp, $value, $widget)
 {
     if ('MetaModelsFilterRangeDateRgXp' !== $rgxp) {
         return;
     }
     $format = $widget->dateformat;
     if (!preg_match('~^' . Date::getRegexp($format) . '$~i', $value)) {
         $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['date'], Date::getInputFormat($format)));
     } else {
         // Validate the date (see https://github.com/contao/core/issues/5086)
         try {
             new Date($value, $format);
         } catch (\OutOfBoundsException $e) {
             $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $value));
         }
     }
 }