PHP正则匹配日期和时间(时间戳转换)的实例代码
(编辑:jimmy 日期: 2025/10/24 浏览:3 次 )
先来一个比较简单实用的代码
日期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正则判断,以下是代码:
<"2016-12-14 23:59:59";
$patten = "/^\d{4}[\-](0";
if (preg_match($patten, $time)) {
echo $timestro = strtotime($time);
} else {
echo "error";
}
"htmlcode">
<meta charset='utf-8'>
<pre>
<"嘿嘿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>
以上就是关于php 日期时间的正则内容,当然很多都是前端js验证的。大家可以参考其他的文章
下一篇:Thinkphp整合微信支付功能