在
这样的页面中<img src="http://www.sito.com/folder/folderb/10/12/2014/text.html" alt="" />
<p>date 15/02/2015</p>
使用reg exp
$result = preg_match_all("/[0-9]{1,2}\/*\-*[0-9]{1,2}\/*\-*[0-9]{4}/", $page, $matches);
$匹配返回
2014年10月12日
15/02/2015
但正如您所看到的,第一个不是日期,但它是网址的一部分。 如何更改正则表达式,如果在单个结果前面有斜杠(/),它还没有返回找到的日期?
答案 0 :(得分:0)
使用negative lookbehind assertion:
$result = preg_match_all("~(?<![/\d-])[0-9]{1,2}[/-]?[0-9]{1,2}[/-]?[0-9]{4}~", $page, $matches);
<强>解释强>
(?<![/\d-]) # Assert that the previous character is not a slash nor a digit nor a dash
[0-9]{1,2} # Match 1-2 digits
[/-]? # Match an optional slash or dash
[0-9]{1,2} # Match 1-2 digits
[/-]? # Match an optional slash or dash
[0-9]{4} # Match 4 digits.
我已使用~
作为正则表达式分隔符,以避免必须转义正则表达式中的斜杠。