Aniket Singh
Aniket Singh

Reputation: 877

How to change every link href value to different url

I'm trying to change every url in a paragraph to encrypted url, so i can track all clicks on outgoing links for e.g

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

I want to get every above url and encrypt them and replace them.

Suppose i got example.com change it into mywebsite.com/track/<?=encrypt("example.com")?>. and finally paragraph should look like this

$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>";

Here is What I've tried

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

Upvotes: 1

Views: 121

Answers (1)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Using preg_match or preg_replace for HTML string is a very bad idea you should use,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();

Upvotes: 1

Related Questions