PHP正則匹配日期和時間程式碼

來源:互聯網
上載者:User

下面貼出代碼:

 代碼如下 複製代碼

<?php

//匹配時間格式為2012-02-16或2012-02-16 23:59:59前面為0的時候可以不寫
$time = "2012-02-16 23:59:59";
$patten = "/^d{4}[-](0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])(s+(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9]))?$/";
if (preg_match ( $patten, $time )) {
   echo $timestro = strtotime ( $time );
  } else {
   echo "error";
  }
?>

對該正則的分析:

 代碼如下 複製代碼

/^d{4}[-](0?[1-9]|1[012])[-](0?[1-9]|[12][0-9]|3[01])(s+(0?[0-9]|[12][0-3]):(0?[0-9]|[1-5][1-9]):(0?[0-9]|[1-5][1-9]))?$/

/是運算式開始符 最後面的/是運算式的結束符
^字串的開始,即以***開始
$表示字串的結尾,即表示已***結尾
|表示或者
()表示一個單元
d{4}匹配一個4位元,
(-)匹配一個“-”號,
(0?[1-9]|1[012])匹配月份,
(0?[1-9]|[12][0-9]|3[01])匹配天,

(s+(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9]))?

整個匹配時分秒部分,?表示有或者沒有。

最後一步就是對匹配成功的進行時間戳記轉換

當前轉換結果為:1329407999

附上我自己寫的執行個體

 代碼如下 複製代碼

<meta charset='utf-8'>
<pre>
<?php
$str="嘿嘿2010/07/08 12:31:56哈哈1999/12/31 13:21:45";
$str2="嘿嘿2010-07-08 12:31:56哈哈1999-12-31 13:21:45";
//僅匹配日期
preg_match_all("/d{4}/d{2}/d{2}/", $str, $arr);
preg_match_all("/d{4}-d{2}-d{2}/", $str2, $arr2);
//匹配日期與時間
preg_match_all("/d{4}/d{2}/d{2}sd{2}:d{2}:d{2}/", $str, $arr3);
preg_match_all("/d{4}-d{2}-d{2}sd{2}:d{2}:d{2}/", $str2, $arr4);
echo '<font color="red">匹配日期</font><br>';
print_r($arr);
print_r($arr2);
echo '<font color="red">匹配日期和時間</font><br>';
print_r($arr3);
print_r($arr4);
?>
</pre>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.