有这样一个需求,要从一个字符串中提取出来时间格式。在网站找了一圈php正则表达式,测试后效果都不太理想,很多还是错误的,严重误导。下面给出一个测试可用的php正则表达式匹配字符串中的时间格式的代码。
正则表达式代码示例如下:
$html = "久久博客www.99xq.cn将在2022-5-26 23:19:59正式改版上线,届时可能存在无法访问的情况,请大家稍安勿躁,最晚在2022-05-27即可恢复访问"; $patten = "/(0?\d{1,4})[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\s([0-9]{1,2}):([0-9]{2}):([0-9]{2})/i"; preg_match_all($patten,$html,$matches); var_dump($matches); //$matches[0][0]就是获取到的时间,支持的格式如下: 1.2022-5-26 23:19:59 2.2022-05-26 23:19:59 3.22-5-26 23:19:59 4.22-5-26 3:19:59 …… 如果你还需要更特殊的,可以调整正则表达式中{}里面的数字,比如{1,2}表示匹配1-2位均可。
通过运行上面代码,可以看到不支持后面的时间提取,因为时间本身是个比较复杂的表现形式,比如跨时区,年月日汉字分割等等。这种情况下可以使用以下方法传递多个正则表达式:
function getMatches($pattern, $subject) { $matches = array(); if (is_array($pattern)) { foreach ($pattern as $p) { $m = getMatches($p, $subject); foreach ($m as $key => $match) { if (isset($matches[$key])) { $matches[$key] = array_merge($matches[$key], $m[$key]); } else { $matches[$key] = $m[$key]; } } } } else { preg_match_all($pattern, $subject, $matches); } return $matches; } $patterns = array( '/<span>(.*?)<\/span>/', '/<a href=".*?">(.*?)<\/a>/' ); $html = '<span>some text</span>'; $html .= '<span>some text in another span</span>'; $html .= '<a href="https://www.99xq.cn/php/449.html">here is the link</a>'; $html .= '<address>address is here</address>'; $html .= '<span>here is one more span</span>'; $matches = getMatches($patterns, $html); print_r($matches);
还有不明白的欢迎留言交流,本文原创自 https://www.99xq.cn/php/449.html
是的,全是代码,我看不懂呀!但是这改变不了我来支持一下!初次见面,申请友链,如若不换,我再发一遍!