【问题标题】:Regex to extract all window.location occurences from a HTML document using PHP使用 PHP 从 HTML 文档中提取所有 window.location 出现的正则表达式
【发布时间】:2016-12-05 16:47:00
【问题描述】:

如何提取 PHP 中出现的所有 window.location?我正在使用 cURL 读取一系列 URL,将其 HTML 内容存储为字符串,并希望匹配所有 window.location 出现并分别输出它们。我尝试了以下方法,但似乎不起作用。 TIA。

$str = 'window.location = "http://www.example.com";
        window.location.href = "http://www.example.com";
        window.location.assign("http://www.example.com");
        window.location.replace("http://www.example.com");
        self.location = "http://www.example.com";
        top.location = "http://www.example.com";
        ';
preg_match('(window\\.location*)', $str,$result);
print_r($result);

【问题讨论】:

  • 您需要preg_match_all 而不仅仅是preg_match
  • 您要显示网址,即http://www.example.com 还是只显示window.location
  • 只有一个示例只有window.location。是否应该找到所有这些 URL?也许window\.location\h*=\h*("|')(.*?)\1...regex101.com/r/PXYyOY/1 或更新问题应该是什么结果。
  • 最好通过换行符将字符串拆分为一个数组,并对每一行进行正则表达式。这将不起作用'(window\\.location*)' 它从第一次出现到文件末尾抓取一部分。
  • ideone.com/ZdNmLh,你需要使用preg_match_all并将*替换为.*

标签: javascript php regex


【解决方案1】:

我知道您想要的是所有 URL(双引号内的内容),而不是重复多次“window.location”的数组:

http://phpfiddle.org/main/code/jg36-u109查看工作代码

$regex[0] = '/window.location(\.href|\.assign)?\s*=\s*"(.+)"/i';
$regex[1] = '/window.location(\.assign|\.replace)\("(.+)"/i';
$regex[3] = '/(self|top)\.location\s*=\s*"(.+)"/i';

$urls = [];
foreach ($regex as $i => $r) {
    preg_match_all($regex[$i], $str, $matches);
    if (!empty($matches[2])) {
        $urls = array_merge($urls, $matches[2]);
    }
}

模式非常不同,我在上面创建了 3 个正则表达式,而不是一个非常复杂的正则表达式。您可以遍历这 3 个,使用 preg_match_all,获取第二组 (.+) 的内容,并将每个结果附加到一个数组中,这将得到您的最终结果:一个包含所有 URL 的数组。

【讨论】:

  • 我在这个列表中又添加了一个正则表达式。就是验证<meta http-equiv="refresh" content="1;url=http://example.com" />。正则表达式是|(?:http-equiv="refresh".*?)?content="\d+;url=(.*?)"(?:.*?http-equiv="refresh")?|i 问题是,如果content=" 1content="1; url=... 之间有空格,则不适用这里需要更改的内容
  • \s* 将匹配零个或多个空白字符。我在上面的 3 个正则表达式中的 = 之前和之后这样做。
【解决方案2】:

Thr preg_match 函数找到第一个模式匹配,你需要使用preg_match_all。但是,您的 window\\.location* 模式与 window.locationnnnnnn 一样匹配 stringsn(* 量词设置为 n 字符)。您需要使用 .* 而不是 * 来匹配除换行符以外的任何 0+ 字符。

所以,对于问题中的字符串,你可以使用

$str = 'window.location = "http://www.example.com";
        window.location.href = "http://www.example.com";
        window.location.assign("http://www.example.com");
        window.location.replace("http://www.example.com");
        self.location = "http://www.example.com";
        top.location = "http://www.example.com";
        ';
preg_match_all('~window\.location.*~', $str,$result);
print_r($result);

PHP demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2013-06-25
    • 2011-09-21
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    相关资源
    最近更新 更多