【问题标题】:Regular expression, how to find all A tags which do not contain tag IMG inside it?正则表达式,如何找出里面所有不包含标签IMG的A标签?
【发布时间】:2010-05-24 09:58:08
【问题描述】:

假设我们有这样的 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);

但我如何告诉它排除包含&lt;img 子字符串的结果在&lt;a href=""&gt;&lt;/a&gt; 内?

【问题讨论】:

  • 不要使用正则表达式解析 HTML :-)
  • 我同意你的观点,但我仍然对使用正则表达式从结果中排除某些单词的方法感兴趣。

标签: php regex regex-negation


【解决方案1】:

您需要使用像Simple DOM parser 这样的HTML 解析器。你cannot parse HTML with regular expressions

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 2013-05-21
      • 2016-06-03
      • 2021-09-23
      • 1970-01-01
      相关资源
      最近更新 更多