【问题标题】:Positive and negative Regular Expression in one preg_match()? [duplicate]一个preg_match()中的正负正则表达式? [复制]
【发布时间】:2020-09-30 16:39:39
【问题描述】:

我想把一个正则表达式和一个负正则表达式放在一个 preg_match() 中。这可能吗?

我使用这些 if 条件。

if ( preg_match('/bot|crawler|spider|/i', $user_agent) )
{
            if ( preg_match('/google|duckduck|yandex|baidu|yahoo|/i', $user_agent) )
            {
                $post['url'] = $url;
            }
            else
            {
                // nothing
            }
}

并且想将代码简化为只有一个 preg_match ...类似这些

if ( preg_match('/bot|crawler|spider|/^(?!/google|duckduck|yandex|baidu|yahoo|/).i', $user_agent) )
      
   $post['url'] = $url;

}

但它不是那样工作的

【问题讨论】:

  • 所以你试图匹配任何有bot|crawler|spider的用户代理,在字符串的某个地方没有google|duckduck|yandex|baidu|yahoo?顺便说一句,您的原始 PHP 代码并没有这样做,它匹配两者而不是否定第二个。
  • 嗨 BadeHorsie,是的,没错。我尝试匹配包含诸如“Bot”之类的单词但不包含诸如“Google”之类的单词的用户代理。

标签: php regex preg-match preg-match-all


【解决方案1】:

如果您想确保“bot”一词出现在任何地方,并且“google”一词不出现在任何地方(在“bot”之前或之后),您可以同时使用正面和负面的前瞻。

if (preg_match('/^(?=.*(bot|crawler|spider))(?!.*(google|duckduck|yandex|baidu|yahoo)).*/i', $user_agent)) {

【讨论】:

  • 我用这个用户代理字符串“Mozilla/5.0(兼容;Yandexbot/2.​​0;+yandex.com/yandexbot.htm)”来测试它,但是这个请求也被 preg_match 阻止了。第一部分似乎工作正常,但在第二部分似乎有一个错误
  • BadHorsie,你是我的英雄。现在它正在工作。非常感谢您的帮助。
猜你喜欢
  • 2012-01-05
  • 1970-01-01
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
相关资源
最近更新 更多