Php 如何用超过4位的数字阻止年份?

Php 如何用超过4位的数字阻止年份?,php,symfony,date,twig,Php,Symfony,Date,Twig,在这种情况下,我使用twig,当用户错误地输入了日期,如2017年5月15日(欧洲格式,我们只使用这一个),twig无法解析日期 ("DateTime::__construct(): Failed to parse time string (12.04.20177) at position 10 (7): Unexpected character"). 我尝试过预匹配、字符串比较、日期比较,但没有任何效果 if (!preg_match("/^[0-9]{2}.[0-9]{2}

在这种情况下,我使用twig,当用户错误地输入了日期,如2017年5月15日(欧洲格式,我们只使用这一个),twig无法解析日期

("DateTime::__construct(): Failed to parse time string (12.04.20177) at position 10 (7): Unexpected character").
我尝试过预匹配、字符串比较、日期比较,但没有任何效果

        if (!preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $date)) {
            throw new RuntimeException("Bug of year 10'000.");
        }

可以在此处添加修复程序:

        $this->twig->addFilter(new Twig_SimpleFilter('date', function($date, $formatOrOptions = null, $timezone = null) {

        // Handle a larger option array but keep the backward compatibility with the Twig date helper
        $defaults = [
            'format' => null,
            'timezone' => null,
            'empty_output' => ''
        ];
        if ($formatOrOptions == null || is_string($formatOrOptions)) {
            $options = array_merge($defaults, ['format'=>$formatOrOptions, 'timezone'=> $timezone]);
        }
        elseif (is_array($formatOrOptions)) {
            if ($diff = array_diff(array_keys($formatOrOptions), array_keys($defaults))) {
                throw new RuntimeException("Invalid options: [".implode(', ', $diff)."]");
            }
            $options = array_merge($defaults, $formatOrOptions);
        }
        else {
            throw new RuntimeException("First filter parameter must be a string or an array");
        }

        // This is because by default Twig return the today date for null values
        if ($date == null || $date == '' || $date == '0000-00-00'){
            return $options['empty_output'];
        }

        return twig_date_format_filter($this->twig, $date, $options['format'], $options['timezone']);

谢谢,对于这个“愚蠢”的问题,我很抱歉:)

您可以尝试传递DateTime对象,而不是将字符串传递给Twig。这样,日期格式验证可以直接在PHP代码中完成。在将变量传递到您的Twig环境之前,您应该尝试构建DateTime对象,如下所示:

$myDate = DateTime::createFromFormat('d.m.Y', $stringDate);
然后应该检查日期变量的内容。如果为false,则解析失败。这样检查:

// Do a strict equality check here
if ($myDate === false) {
    throw new RuntimeException("Invalid date");
}
当然,根据您的需要,以您认为最合适的方式处理您的异常。这只是一个例子

然后可以传递$myDate变量而不是字符串,并将其集成到细枝模板中

{{ myDate|date(d.m.Y) }}

使用正则表达式。此外,您还可以使用HTML5日期输入。@Twinfriends我已经尝试过了:(对于HTML5输入,我们有这个
为什么不使用
try{new\DateTime($string);}catch(\Exception$e){/**无效日期**/}
@DarkBee我将尝试它;)thanks@RomainSickenberg
type=“text”
-当您输入的是文本时,您希望得到什么?它会自动验证吗?正如我所说,了解HTML5类型的输入。您只需更改“文本”一词,一切都会正常工作:)
// Do a strict equality check here
if ($myDate === false) {
    throw new RuntimeException("Invalid date");
}
{{ myDate|date(d.m.Y) }}