PHP DOM获取网站所有脚本src

时间:2015-09-08 18:25:19

标签: javascript php dom preg-match

我想使用curl和DOM从网站获取所有脚本src链接。

我有这段代码:

$scripts = $dom->getElementsByTagName('script');

foreach ($scripts as $scripts1) {

    if($scripts1->getAttribute('src')) {

        echo $scripts1->getAttribute('src');

    }

}

此脚本工作正常,但如果网站有这样的脚本标记会发生什么:

<script type="text/javascript">
window._wpemojiSettings = {"source":{"concatemoji":"http:\/\/domain.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.2.4"}}; ........
</script>

我还需要获取此脚本src。我怎么能这样做?

1 个答案:

答案 0 :(得分:-1)

如果你的第一个解析器是空的,我会用正则表达式创建另一个,即:

$html = file_get_contents("http://somesite.com/");

preg_match_all('/<script.*?(http.*?\.js(?:\?.*?)?)"/si', $html, $matches, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($matches[1]); $i++) {
    echo str_replace("\\/", "/", $matches[1][$i]);
}

您可能需要调整正则表达式才能使用不同的网站,但上面的代码可以让您了解所需内容。

样本: http://ideone.com/Fwf6Mb

正则表达式解释:

<script.*?(http.*?\.js(?:\?.*?)?)"
----------------------------------

Match the character string “<script” literally «<script»
Match any single character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the regex below and capture its match into backreference number 1 «(http.*?\.js(?:\?.*?)?)»
   Match the character string “http” literally «http»
   Match any single character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match the character “.” literally «\.»
   Match the character string “js” literally «js»
   Match the regular expression below «(?:\?.*?)?»
      Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
      Match the character “?” literally «\?»
      Match any single character «.*?»
         Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “"” literally «"»

正则表达式教程

http://www.regular-expressions.info/tutorial.html