如何找到网页中的所有链接(URL)并在所有链接的末尾添加一个字符串?

时间:2015-03-26 05:44:55

标签: php html regex string web-crawler

嘿所以我想要实现的是使用

获取页面上的所有链接
preg_match_all("/<a(?:[^>]*)href=\"([^\"]*)\"(?:[^>]*)>(?:[^<]*)<\/a>/is"

然后在每个网址的末尾添加“| Cookie =”,同时保持页面源完全相同。

例如: 假设我在抓取页面中找到以下链接“example.com/index.htmlexample2.com/index.html

我希望将它们更改为“example.com/index.html|Cookie=xxx”和“example2.com/index.html|Cookie=xxx

很抱歉,如果我的问题太模糊了。我不知道如何开始:(

2 个答案:

答案 0 :(得分:1)

您不需要正则表达式,您可以使用 DOM 为您执行此操作。

$doc = new DOMDocument;
@$doc->loadHTML($html); // load the HTML data

foreach ($doc->getElementsByTagName('a') as $link) {
   $link->setAttribute('href', $link->getAttribute('href').'|Cookie=xxx');
}

echo $doc->saveHTML();

答案 1 :(得分:0)

如果你有网址,只需替换$content = file_get_contents('URL');

<?php

$content = '<html>
<title>Random Website I am Crawling</title>
<body>
Click <a href="http://clicklink.com">here</a> for foobar
Another site is http://foobar.com
</body>
</html>';

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor

$pattern = "/$regex/";

$newContent = preg_replace($pattern, '${0}|Cookie=xxx', $content);
echo $newContent;

输出:

<html>
<title>Random Website I am Crawling</title>
<body>
Click <a href="http://clicklink.com|Cookie=xxx">here</a> for foobar
Another site is http://foobar.com|Cookie=xxx
</body>