php匹配字符串中切合的时间名目标内容

这个函数的浸染是php匹配字符串中含有时间名目标内容,返回匹配的时间数组。我也想不到我会写这个函数,至于实用性各人就仁者见仁,智者见智了。在正则上面我写了切合1900年到2099年的时间名目。

<?php /* 查找字符串中切合的时间名目标内容 by enenba @param str $str @param str $basetime 必然要包括的时间 'month'包括月日 / 'hour' 包括时分 @return array 'total'=> 含有时间名目标数量 ; 'array_time'=> 时间数组 */ function get_time_str($str,$basetime='month') { if ($basetime!='month'){ //包括时分 $preg='/(?:19|20)?(?:[0-9]{2})?(?:-|\s|\/|\.|年)?(?:0[1-9]|1[012])?(?:-|\s|\/|\.|月)?(?:0[1-9]|[12][0-9]|3[01])?(?:日)?\s?(?:[01][0-9]|2[1-4])(?::|小时|时)(?:[0-6]?[0-9])(?::|分)?(?:[0-6]?[0-9])?(?:秒)?/i'; }else{ //包括月日 $preg='/(?:19|20)?(?:[0-9]{2})?(?:-|\s|\/|\.|年)?(?:0[1-9]|1[012])(?:-|\s|\/|\.|月)(?:0[1-9]|[12][0-9]|3[01])(?:日)?\s?(?:[01][0-9]|2[1-4])?(?::|小时|时)?(?:[0-6]?[0-9])?(?::|分)?(?:[0-6]?[0-9])?(?:秒)?/i'; } $n = preg_match_all($preg, $str, $rr); return array('total'=>$n,'array_time'=>$rr); } //以下为测试 $str=' 2012/02/02 12:12:12开始大幅拉 萨各人12:01舍得分开 开2012年02月02日为量面目一新一本 房间。开2012年02月02日 18时10分10秒始 大幅2012年02月02日 18时10分拉萨 各人2012年02月02日 12:12舍得离 开2012年02月02日房间2012-02-02 '; $rr = get_time_str($str); echo '有'.$rr["total"].'个时间数据'; printf("<p>输出时间数据为:</p><pre>%s</pre>\n",var_export( $rr[array_time] ,TRUE)); /* 有7个时间数据 输出时间数据为: array ( 0 => array ( 0 => '2012/02/02 12:12:12', 1 => '2012年02月02日', 2 => '2012年02月02日 18时10分10秒', 3 => '2012年02月02日 18时10分', 4 => '2012年02月02日 12:12', 5 => '2012年02月02日', 6 => '2012-02-02', ), ) */ ?>

以下附件正则表明:

end

附件下载/演示源码:
【 match_time.htm 】 33.79KB

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/7849.html