【问题标题】:Search consecutive 'User-agent' directive in robots.txt with PHP使用 PHP 在 robots.txt 中搜索连续的“用户代理”指令
【发布时间】:2017-02-08 17:43:35
【问题描述】:

使用 PHP,我想检查 (true/false) robots.txt 文件中是否有连续的“用户代理”指令。

使用这个正则表达式,preg_match('~User-agent:\h*(?:\R|$)~i', $string) 我找到了所有 'User-agent:' 行,但我还没有找到如何检测连续行。

User-agent:    # 'User-agent:'
\h*            # horizontal whitespace (0 or more times)
(?:            # group, but do not capture:
  \R           #   '\R' (any Unicode newline sequence) 
 |             #  OR
  $            #   before an optional \n, and the end of the string
)              # end of grouping

例如

User-agent: 008
user-agent: Accoona
User-Agent: Googlebot
User-Agent: aipbot*
disallow: /

结果:正确

User-Agent: Googlebot
Crawl-delay: 60
User-agent: aipbot*
disallow: /

结果:错误

User-agent: 008
Crawl-delay: 2
user-agent: Accoona
User-Agent: Googlebot
User-Agent: aipbot*
disallow: /

结果:正确

【问题讨论】:

    标签: php regex robots.txt


    【解决方案1】:

    这似乎是一个愚蠢的答案,但为什么不重复你的正则表达式呢? User-agent:\h*(?:[a-zA-Z0-9\*]*\R|$)User-agent:\h*(?:[a-zA-Z0-9\*]*\R|$) 肯定只有在有两个连续的用户代理时才匹配?

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

    在连续的 0 个匹配项之间添加/删除非用户代理行。连续两行导致匹配。

    【讨论】:

    • 我在这儿!但是用户代理描述中可能有任何空白字符。我用[a-zA-Z0-9 \*] (regex101.com/r/ximRMo/4) 来捕捉它。
    【解决方案2】:

    没有正则表达式:

    $filePath = 'robots.txt';
    
    try {
        if ( false === $fh = fopen($filePath, 'rb') )
            throw new Exception('Could not open the file!');
    
    } catch (Exception $e) {
        echo 'Error (File: ' . $e->getFile() . ', line ' . $e->getLine() . '): ' . $e->getMessage();
    }
    
    var_dump(hasSuccessiveUA($fh));
    
    fclose($fh);    
    
    function hasSuccessiveUA($fh) {
        $previous = false;
    
        while ( false !== $line = fgets($fh) ) {
            $current = ( stripos($line, 'user-agent:') === 0 );
            if ( $previous && $current ) return true;
            $previous = $current;
        }
    
        return false;
    }
    

    优点:当答案为真时,您不必加载文件直到结束。

    【讨论】:

      猜你喜欢
      • 2013-09-24
      • 2012-12-13
      • 2013-01-20
      • 2014-03-27
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多