【问题标题】:Exclude site url from links RegEx从链接 RegEx 中排除网站 url
【发布时间】:2018-12-03 19:22:44
【问题描述】:

我有一个正在使用的正则表达式,用于列出在给定 html 内容中找到的所有链接

<a\s[^>]*href=(\"??)(http[^\" >]*?)\\1[^>]*>(.*)<\/a>

这实际上工作得很好,现在的问题是我想从结果中排除所有内部链接(乍一看,只得到包括“http”的那些就足够了,但不幸的是很多内部“绝对”链接..)

鉴于我知道网站 url,我不需要帮助来获得它,所以我们假设是 www.test.com / test.com

我查看了 Negative Lookahead 参考,但我不确定它应该如何在现有的 RegEx 中实现..

谢谢 干杯

【问题讨论】:

标签: php regex preg-match pcre


【解决方案1】:

最简单的方法是使用替代方法创建网站黑名单
结合(*SKIP)(*FAIL)
这样,引擎就会越过有问题的 url,并且不能回溯。

(?:<a(?=\s)(?=(?:[^>"']|"[^"]*"|'[^']*')*?\shref\s*=\s*(?:(['"])(?:(?!\1)[\S\s])*?(?:www\.test\.com|test\.com)(?:(?!\1)[\S\s])*?\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>.*?</a\s*>(*SKIP)(*FAIL)|<a(?=\s)(?=(?:[^>"']|"[^"]*"|'[^']*')*?\shref\s*=\s*(?:(['"])([\S\s]*?)\2))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]*?)+>(.*?)</a\s*>)

https://regex101.com/r/hpwUr3/1

你想要的东西是:
- 第 3 组 = 网址
- 第 4 组 = 内容

解释

 (?:
      # Begin Offender Anchor tag
      < a
      (?= \s )
      (?=                           # Asserttion for:  href  (a pseudo atomic group)
           (?: [^>"'] | " [^"]* " | ' [^']* ' )*?
           \s href \s* = \s* 
           (?:
                ( ['"] )                      # (1)
                (?:
                     (?! \1 )
                     [\S\s] 
                )*?
                (?:                           # Add more offenders here
                     www \. test \. com
                  |  test \. com 
                )
                (?:
                     (?! \1 )
                     [\S\s] 
                )*?
                \1 
           )
      )
                                    # Have the href offendeer, just match the rest of tag
      \s+ 
      (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+

      >                             # End  tag

      .*? 
      </a \s* >
      (*SKIP) (*FAIL)               # Move past the offender
   |  

      # Begin Good Anchor tag
      < a
      (?= \s )
      (?=                           # Asserttion for:  href  (a pseudo atomic group)
           (?: [^>"'] | " [^"]* " | ' [^']* ' )*?
           \s href \s* = \s* 
           (?:
                ( ['"] )                      # (2)
                ( [\S\s]*? )                  # (3), Good link
                \2 
           )
      )
                                    # Have the href good one, just match the rest of tag
      \s+ 
      (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+

      >                             # End  tag

      ( .*? )                       # (4), Content
      </a \s* >
 )

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 2011-10-26
    • 1970-01-01
    • 2015-01-26
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多