验证DateTime :: modify()的字符串输入 [英] Validate string input for DateTime::modify()

查看:39
本文介绍了验证DateTime :: modify()的字符串输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况是从用户编辑的数据库中读取发送到 DateTime :: modify($ string) $ string 变量,我该如何验证 $ string DateTime :: modify()吗?

I have as scenario where the $string variable sent to DateTime::modify($string) is read from a database edited by users, how can i validate that $string is a proper string for DateTime::modify() ?

推荐答案

您可以执行以下操作,并在将字符串传递给实际日期之前调用它:

You could do something like this, and call it before you pass the string into your actual date:

function modifyIsValid($modifyString) {
    $d = new DateTime();
    $isValid = $d->modify($modifyString);

    if ($isValid === false) {
        return false;
    }

    return true;
}

-> modify()如果传递的字符串无效,则返回false,尽管这也会抛出一个不理想的 E_Warning .

->modify() returns false is the string passed is not valid, although it will also throw up an E_Warning which is not ideal.

$d = new DateTime();
$string = 'not a valid modifier';

if (modifyIsValid($string)) {
    // Continue 
}  else {
    // Print a friendly error message.
}

您可以在手册中找到有关它的更多信息: http://php.net/manual/en/datetime.modify.php

You can find more information about it in the manual: http://php.net/manual/en/datetime.modify.php

希望有帮助.

这篇关于验证DateTime :: modify()的字符串输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆