【问题标题】:How to explode date from a string using php preg_match and regex如何使用 php preg_match 和 regex 从字符串中分解日期
【发布时间】:2009-10-27 00:53:40
【问题描述】:

我正在处理其中某处带有日期的字符串。日期在此字符串中的显示方式有多种:

"… 01.11.2009 18:00-21:00 …" 或 “…… 01.11.2009 18:00-02.11.2009 15:00……”或 “……2009 年 11 月 1 日 18:00……”

无论日期如何显示,我只需要开始日期“01.11.2009 18:00”。因此,如果有两场比赛,那就是第一场比赛。如何从 php.ini 中的完整字符串中分离/分解它。有什么想法吗?

我想我需要用正则表达式创建一个模式,然后用 preg_match 匹配它。是这样吗?不幸的是,我不太喜欢正则表达式。谁能帮忙从随机字符串中获取我的单个日期块?

【问题讨论】:

    标签: php regex date preg-match


    【解决方案1】:
    $matches = array();
    $desired_date = '';
    preg_match('/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/', $string_containing_dates, $matches);
    if (isset($matches[0])) $desired_date = $matches[0];
    

    【讨论】:

      【解决方案2】:

      试试:

      $s = "… 01.11.2009 18:00-21:00 …… 01.11.2009 18:00-02.11.2009 15:00 …… 01.11.2009 18:00 …";
      preg_match_all('!(\d{2}\.\d{2}\.\d{4}) \d{2}:\d{2}(-\d{2}:\d{2}|-\d{2}\.\d{2}\.\d{4} \d{2}:\d{2})?!', $s, $matches);
      print_r($matches[1]);
      

      【讨论】:

        【解决方案3】:

        如果您的日期按以下方式格式化,则每个日期的字符数将始终相同。然后,您可以使用简单的 substr() 来获取开始的 X 字符:

        // example date strings
        $date = date('m.d.Y h:i:S');
        $date2 = date('m.d.Y h:i:S', strtotime('+50 days'));
        $date_str = $date . '-' . $date2;
        
        // get the first 10 characters for the date
        $match = substr($date_str, 0, 10);
        

        【讨论】:

          【解决方案4】:

          试试这个:

          preg_match_all(
              '/([0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2})' // linebreak added
              . '(?:-(?:[0-9]{2}\.[0-9]{2}\.[0-9]{4} )?(?:[0-9]{2}:[0-9]{2})?)?/',
              '" 01.11.2009 18:00-21:00 " or " 01.12.2009 18:00-02.12.2009 15:00 " '
              . 'or " 01.01.2009 18:00 "',
              $matches
          );
          
          print_r($matches[1]);
          // "01.11.2009", "01.12.2009", "01.01.2009"
          

          【讨论】:

            【解决方案5】:

            您可以使用以下函数提取该格式的第一个日期:

            function find_date($string) {
                preg_match("/\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}/",$string,$matches);
                return $matches[0];
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-07-06
              • 1970-01-01
              • 2019-12-22
              • 1970-01-01
              • 1970-01-01
              • 2019-03-17
              • 2011-10-20
              • 2021-11-29
              相关资源
              最近更新 更多