如何将每个 link href 值更改为不同的 url

How to change every link href value to different url

我正在尝试将段落中的每个 url 更改为加密 url,这样我就可以跟踪对传出链接的所有点击,例如

$paragraph = "<p>This is an example <a href='example.com'>My Website</a></p>
<h2><a href="example2.com">another outgoing link</a></h2>";

我想获取上面的每一个 url 并加密并替换它们。

假设我得到 example.com 将其更改为 mywebsite.com/track/<?=encrypt("example.com")?>。最后一段应该是这样的

$paragraph = "<p>This is an example <a href='mywebsite.com/track/29abbbbc-48f1-4207-827e-229c587be7dc'>My Website</a></p>
<h2><a href="mywebsite.com/track/91hsksc-93f1-4207-827e-839c5u7sbejs"></a></h2>";

这是我试过的方法

$message = preg_replace("/<a([^>]+)href=\"http\:\/\/([a-z\d\-]+\.[a-z\d]+\.[a-z]{2,5}(\/[^\"]*)?)/i", "<ahref=\"encrypted url", $message);

HTML 字符串使用 preg_matchpreg_replace 是一个非常糟糕的主意,你应该使用,DOMDocument

Try this code snippet here

<?php

ini_set('display_errors', 1);
$paragraph = "<p>This is an example <a href='example.com'>My Website</a></p>
<h2><a href=\"example2.com\"></a></h2>";

$domDocument= new DOMDocument();
$domDocument->loadHTML($paragraph,LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
//getting all nodes with tagname a
$results=$domDocument->getElementsByTagName("a");

foreach($results as $resultantNode)
{
    $href=$resultantNode->getAttribute("href");//getting href attribute
    $resultantNode->setAttribute("href","mywebsite.com/track/"."yourEncoded:$href");//replacing with the value you want.
}
echo $domDocument->saveHTML();