PHP正則匹配日期和時間戳記轉換案例詳解

來源:互聯網
上載者:User
本文介紹下,用php實現正則匹配日期與時間,並進行時間戳記轉換的例子,有需要的朋友,參考下吧

先來一個比較簡單實用的代碼

日期YYYY-MM-DD


$str = '';$isMatched = preg_match('/^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/', $str, $matches);var_dump($isMatched, $matches);


php需要一定的時間格式才能轉換成時間戳記(表示從格林威治時間1970年01月01日00時00分00秒起至現在的總秒數),這就要用到php正則判斷,以下是代碼:


<?php//匹配時間格式為2016-02-16或2016-02-16 23:59:59前面為0時可以不寫$time = "2016-12-14 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.