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

How find all links (URL) in a webpage and add a string at the end of all of them?

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

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

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

例如: 假设我在抓取的页面“example.com/index.htmlexample2.com/index.html

中找到以下链接

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

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

如果你有 url 只需替换 $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, '[=10=]|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>

您不需要正则表达式,您可以使用 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();