1

我需要 PHP 中的正则表达式来在 URL 中找到 http-equiv="refresh" 元标记。我需要的是要遵循的实际 URL。现在,据我所知,有两种使用此元标记的有效方法:

content="0; url=urlhere" http-equiv="refresh" />

http-equiv="refresh" content="0; url=urlhere"/>

谢谢!

4

2 回答 2

7

迪玛,

尝试这个:

<?
  preg_match('|content="\d+;url=(.*?)"|i', '<META HTTP-EQUIV="Refresh" CONTENT="5;URL=http://www.stackoverflow.com">', $res1);
  preg_match('|content="\d+;url=(.*?)"|i', '<META CONTENT="5;URL=http://www.stackoverflow.com" HTTP-EQUIV="Refresh">', $res2);

  echo "<pre>";
  var_dump($res1);
  var_dump($res2);
  echo "</pre>";
?>

输出:

array(2) {
  [0]=>
  string(44) "CONTENT="5;URL=http://www.stackoverflow.com""
  [1]=>
  string(28) "http://www.stackoverflow.com"
}
array(2) {
  [0]=>
  string(44) "CONTENT="5;URL=http://www.stackoverflow.com""
  [1]=>
  string(28) "http://www.stackoverflow.com"
}

请记住,您必须处理空格(在内容属性内、标签之间、在 http-equiv 属性内等),例如:

<META HTTP-EQUIV="Refresh" CONTENT=" 5 ; URL=http://www.stackoverflow.com ">

以下代码片段处理这种情况:

<?
  preg_match('|content="\s*\d+\s*;\s*url=(.*?)\s*"|i', '<META HTTP-EQUIV="Refresh" CONTENT=" 5 ; URL=http://www.stackoverflow.com ">', $res3);

  echo "<pre>";
  var_dump($res3);
  echo "</pre>";
?>

输出:

array(2) {
  [0]=>
  string(48) "CONTENT=" 5 ; URL=http://www.stackoverflow.com ""
  [1]=>
  string(28) "http://www.stackoverflow.com"
}

最后,如果这还不够,您可以检查内容属性每一侧的 http-equiv="refresh" (始终考虑空白),如下所示:

<?
  preg_match('|(?:http-equiv="refresh".*?)?content="\d+;url=(.*?)"(?:.*?http-equiv="refresh")?|i', '<META HTTP-EQUIV="Refresh" CONTENT="5;URL=http://www.stackoverflow.com">', $res4);
  preg_match('|(?:http-equiv="refresh".*?)?content="\d+;url=(.*?)"(?:.*?http-equiv="refresh")?|i', '<META CONTENT="5;URL=http://www.stackoverflow.com" HTTP-EQUIV="Refresh">', $res5);  


  echo "<pre>";
  var_dump($res4);
  var_dump($res5);
  echo "</pre>";
?>

输出:

array(2) {
  [0]=>
  string(44) "CONTENT="5;URL=http://www.stackoverflow.com""
  [1]=>
  string(32) "http://www.stackoverflow.com"
}
array(2) {
  [0]=>
  string(65) "CONTENT="5;URL=http://www.stackoverflow.com" HTTP-EQUIV="Refresh""
  [1]=>
  string(32) "http://www.stackoverflow.com"
}

您可以使用相同的方法。添加对考虑零件的支持。
此外,请记住始终使用 i 选项运行正则表达式,以启用不区分大小写的匹配。

于 2009-09-03T00:00:53.760 回答
3
http-equiv\W*refresh.+?url\W+?["'](.+?)["']

尝试:

if (preg_match('/meta.+?http-equiv\W+?refresh/i', $x)) {
   preg_match('/content.+?url\W+?["\'](.+?)["\']/i', $x, $matches);
   print_r($matches);
}
于 2009-09-02T20:58:47.277 回答