如何在PHP中使用正则表达式从robots.txt文件中提取站点地图引用?

时间:2012-02-17 23:17:26

标签: php regex sitemap robots.txt

我想解析robots.txt文件并提取站点地图参考。假设文件是​​这样的;

stuff
foobar
Sitemap: http://www.cgdomestics.co.uk/sitemap.xml
hello world
more stuff

我正在尝试使用正则表达式来提取这个;

http://www.cgdomestics.co.uk/sitemap.xml

到目前为止,我有这个PHP代码;

<?php
  $robots_url = "http://www.cgdomestics.co.uk/robots.txt";
  $robots_file = file_get_contents($robots_url);
  $pattern = "/Sitemap: .*/";
  $i = preg_match($pattern, $robots_file, $match);
  echo $match[0];
?>

以上的输出是;

Sitemap: http://www.cgdomestics.co.uk/sitemap.xml

但我希望它只输出;

http://www.cgdomestics.co.uk/sitemap.xml

我可以使用正则表达式准确地返回我想要的内容或者我需要执行另一步来删除“Sitemap:”部分吗?或者有更好的方法吗?

你可能会告诉我,我不常用PHP和正则表达式。

感谢。

3 个答案:

答案 0 :(得分:1)

设置子模式并从匹配数组中获取

<?php
  $robots_url = "http://www.cgdomestics.co.uk/robots.txt";
  $robots_file = file_get_contents($robots_url);
  $pattern = "/Sitemap: ([^\r\n]*)/";
  $i = preg_match($pattern, $robots_file, $match);
  echo $match[1];
?>

答案 1 :(得分:1)

对url使用group(子模式),然后引用该子模式索引(在本例中为1):

  $pattern = "/Sitemap: (.*/)";
  $i = preg_match($pattern, $robots_file, $match);
  echo $match[1]; /*First parenthesized subpattern */

从文档: $ matches [1]将具有与第一个捕获的带括号的子模式匹配的文本。请参阅:http://php.net/manual/en/function.preg-match.php

答案 2 :(得分:0)

preg_match('/Sitemap: ([^\n]*)\n$/',file_get_contents($url),$matches);

print_r($matches);

这对你有什么影响?