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

时间:2017-05-13 10:27:20

标签: php domdocument

我正在尝试将段落中的每个网址更改为加密网址,因此我可以跟踪外发链接上的所有点击次数,例如

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

我希望获得上述每个网址并对其进行加密并替换它们。

假设我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", "<a$1href=\"encrypted url", $message);

1 个答案:

答案 0 :(得分:1)

使用preg_matchpreg_replace代表HTML字符串是您应该使用的一个非常糟糕的主意,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();