如何检查PHP中的数据格式 [英] How to check the data format in PHP

查看:153
本文介绍了如何检查PHP中的数据格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查一个日期格式,看看我可以检查数据变量是否具有像MM-DD-YYYY这样的格式。如果没有,那么exit()。我不知道如何检查格式,如果有任何人可以帮助我,请欣赏。谢谢...

I am trying to check a date format to see if I can check the data variable has certain format like MM-DD-YYYY. if not, then exit(). I am not sure how to check the format and would appreciate if any one can help me about it. Thanks...

$date=05/25/2010;    
if(XXXXX){
    // do something....
}


推荐答案

正如其他人所建议的那样,使用正则表达式。之前发布的那些将接受无效日期,例如99/99/9999。这是一个改进的正则表达式(从 here 生成)

Use a regular expression, as others have suggested. The ones posted before will accept invalid dates such as 99/99/9999 however. Here's an improved regex (lifed from here)

$date_regex = '!^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$!';
if (preg_match($date_regex, $date)) {
   // do something
}

它只会收到有效的日期,它也会接受不同的分隔符(如05.20.2002和05-02-2002)。

It will only take valid dates and it will also accept different separators (such as 05.20.2002 and 05-02-2002).

如果您问我用户体验不好,迫使他们输入特定的格式。您可以使用 strtotime ()处理不同的格式。

If you ask me it's bad user experience to force them to enter a particular format. YOU can handle different formats using strtotime().

这篇关于如何检查PHP中的数据格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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