Reputation: 41
I have a string with HTML tags and I want to encode all link urls with base64.
Example input
<a href="url.com/fqobh2ykscn7" ...>
Expected output
<a href="/link.php?url=base64(url.com/fqobh2ykscn7)" ...>
I've tried many methods, for example:
$string = '<img style="border-style: none;" title="Downloading Links" src="/wp-content/uploads/2011/12/download-links.jpg" alt="Downloading Links" /></h4>
<a href="http://url.com/vp1m8880e4hd" target="blank" rel="nofollow">Uptobox</a>
<a href="http://url2.com/fqobh2ykscn7" target="blank" rel="nofollow">Clickupload</a>
<a href="https://url3.com/ian2dpkgyzio" target="blank" rel="nofollow">Usercloud</a>
Password:<span style="color: #b22222;">url4.com</span>';
echo preg_replace('/<a(.*)href=([a-zA-Z]+)"? ?(.*)>(.*)<\/a>/', '<a href="\3\4>\5</a>', $string);
Upvotes: 1
Views: 759
Reputation: 6511
There are many reasons not to use regex to parse HTML. Instead, we can use the DOM extension.
And to encode with base64, we'll use base64_encode()
.
Code
$string = '
<img style="border-style: none;" title="Downloading Links"
src="/wp-content/uploads/2011/12/download-links.jpg" alt="Downloading Links" /></h4>
<a href="http://url.com/vp1m8880e4hd" target="blank" rel="nofollow">Uptobox</a>
<a href="http://url2.com/fqobh2ykscn7" target="blank" rel="nofollow">Clickupload</a>
<a href="https://url3.com/ian2dpkgyzio" target="blank" rel="nofollow">Usercloud</a>
Password:<span style="color: #b22222;">url4.com</span>';
$dom = new DOMDocument;
@$dom->loadHTML($string, LIBXML_HTML_NODEFDTD);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$anchor->setAttribute('href', 'link.php?url=' . base64_encode($anchor->getAttribute('href')));
}
$result = $dom->saveHTML();
echo $result;
Output
<html><body><img style="border-style: none;" title="Downloading Links" src="/wp-content/uploads/2011/12/download-links.jpg" alt="Downloading Links">
<a href="link.php?url=aHR0cDovL3VybC5jb20vdnAxbTg4ODBlNGhk" target="blank" rel="nofollow">Uptobox</a>
<a href="link.php?url=aHR0cDovL3VybDIuY29tL2Zxb2JoMnlrc2NuNw==" target="blank" rel="nofollow">Clickupload</a>
<a href="link.php?url=aHR0cHM6Ly91cmwzLmNvbS9pYW4yZHBrZ3l6aW8=" target="blank" rel="nofollow">Usercloud</a>
Password:<span style="color: #b22222;">url4.com</span></body></html>
Upvotes: 1