假设我们有这样的HTML代码。我们需要获取所有不包含img标签的<a href=""></a>标签。
<a href="http://domain1.com"><span>Here is link</span></a>
<a href="http://domain2.com" title="">Hello</a>
<a href="http://domain3.com" title=""><img src="" /></a>
<a href="http://domain4" title=""> I'm the image <img src="" /> yeah</a>我使用这个正则表达式来查找所有的a标记链接:
preg_match_all("!<a[^>]+href=\"?'?([^ \"'>]+)\"?'?[^>]*>(.*?)</a>!is", $content, $out);我可以像这样修改它:
preg_match_all("!<a[^>]+href=\"?'?([^ \"'>]+)\"?'?[^>]*>([^<>]+?)</a>!is", $content, $out);但是,我如何告诉它排除<a href=""></a>中包含<img子字符串的结果呢
发布于 2010-05-24 18:45:18
Dom是可行的,但出于兴趣考虑,以下是解决方案:
在正则表达式中排除某些匹配的最简单方法是使用“负前视”或“负后视”。如果在字符串中的任何位置找到负表达式,则匹配失败。
示例:
^(?!.+<img.+)<a href=\"?\'?.+\"?\'?>.+</a>$匹配项:
<a href="http://domain1.com"><span>Here is link</span></a>
<a href="http://domain2.com" title="">Hello</a>但不匹配:
<a href="http://domain3.com" title=""><img src="" /></a>
<a href="http://domain4" title=""> I'm the image <img src="" /> yeah</a>负向展望是字符串的这一部分:
(?!.+<img.+)这表示不匹配任何字符后跟
<a href=\"?\'?.+\"?\'?>.+</a>
其余的是我对html中锚标签的一般匹配,你可能想要使用一个替代的匹配表达式。
根据您的使用情况,您可能需要省略开始和结束^$字符。
有关前瞻/后视的更多信息
http://www.codinghorror.com/blog/2005/10/excluding-matches-with-regular-expressions.html
发布于 2010-05-24 18:04:52
你需要使用像Simple DOM parser这样的超文本标记语言解析器。你是cannot parse HTML with regular expressions。
https://stackoverflow.com/questions/2896088
复制相似问题