【问题标题】:Remove other domains with Regex使用正则表达式删除其他域
【发布时间】:2016-02-07 00:55:21
【问题描述】:

所以我有一个 preg_replace 用“[链接删除]”替换字符串中的所有链接:

/((https?:\/\/)?(\w+\.)+[a-z|A-Z]{2,}(:\d+)?((\/\w+)+(\.\w+)?)?\/?)/

Simplified:
http/https, subdomain, domain, tld, port, folder/file, extension, "/"

但我需要以某种方式进行过滤,如果域是“example.com”,则不会像以下那样被替换:

"http://notmydomain.com" -> "[link removed]"
"example.com" -> "example.com"

【问题讨论】:

  • 如果 url 是 http://example.abc.comhttp://notmydomain.example.com 怎么办?那么输出呢?
  • @A-2-A 哦,你是对的,那么让我们只使用“example.com”
  • 您可以调用一个函数进行替换(我认为是/e 或其他东西)并让函数决定是否替换?

标签: php regex preg-replace


【解决方案1】:

使用negative lookahead assertion

/((https?:\/\/)?(?![^:\/\s]*\bexample\.com)(\b\w+\.)+[a-z|A-Z]{2,}(:\d+)?((\/\w+)+(\.\w+)?)?\/?)/

说明:

(?!            # Assert that it's impossible to match this from the current location:
 [^:\/\s]*     # Any number of characters except colon, slash or whitespace
 \b            # followed by a start-of-word anchor
 example\.com  # followed by example.com.
)              # End of lookahead.

另外,我在\w+ 部分之前添加了另一个word boundary anchor,以确保在将example.com 作为输入时我们不匹配xample.com

测试它live on regex101.com

【讨论】:

  • 如您所见 here 它也匹配 foo.php 之类的文件
  • 是的,你的正则表达式也是如此。
猜你喜欢
  • 2019-02-16
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 2016-04-18
相关资源
最近更新 更多