dongzhan1492 2012-03-24 17:07
浏览 28
已采纳

PHP preg_match mysql时间数据类型,格式为xxx:xx:xx

Looking for the correct preg_match (or other solution) to validate a string to go in mysql time datatype. The format is xxx:xx:xx and between ranges '-838:59:59' to '838:59:59'

Also in mind that "7:53:48", "23:59", "145:19:59", and "-16:24:33" are all valid inputs but "930:00:00", 128:61:61" and "63:59" are all invalid.

I've got this far from a normal time preg_match

preg_match("/([0-9]):([0-5][0-9]):([0-5][0-9])$/", $time)

But this only validates the minutes and seconds properly. Any ideas !?

Also note that I understand that time mysql datatype also accepts values without the colons, but that's been handled separately already ;)

EDIT

I'm really sorry guys, missunderstood mysql doc. 70:59 is actually valid input, it will be translated to 70:59:00

  • 写回答

2条回答 默认 最新

  • douyouzheng2209 2012-03-24 17:24
    关注
    (?<![0-9:])-?([0-9]|[0-9][0-9]|[0-7][0-9][0-9]|8[0-2][0-9]|83[0-8]):([0-5][0-9])(?::([0-5][0-9]))?(?![0-9:])
    

    Explanation:

    (?<!                  # look-behind: makes sure we are at the start of a time
      [0-9:]              #   ...not preceded by a digit or a colon
    )                     # end look-behind
    -?                    # a minus, optional
    (                     # group 1 (hours)
       [0-9]              #   single-digit 0-9
       |                  #   or
       [0-9][0-9]         #   double-digit 00-99
       |                  #   or
       [1-7][0-9][0-9]    #   triple-digit 100-799
       |                  #   or
       8[0-2][0-9]        #   triple-digit 800-829
       |                  #   or
       83[0-8]            #   triple-digit 830-838
    )                     # end group 1
    :                     # :
    (                     # group 2 (minutes)
       [0-5][0-9]         #   00-59
    )                     # end group 2
    (?:                   # non-capturing group
      :                   #   :
      (                   #   group 3 (seconds)
        [0-5][0-9]        #     00-59
      )                   #   end group 3
    )?                    # end group, make optional
    (?!                   # look-ahead: makes sure we are at the end of a time
      [0-9:]              #   ...not followed by a digit or a colon
    )                     # end look-ahead
    

    This actually matches time strings in a larger text, instead of just validating them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?