我有一个带HTML标签的字符串,我想用base64编码所有链接网址。
示例输入
<a href="url.com/fqobh2ykscn7" ...>
预期输出
<a href="/link.php?url=base64(url.com/fqobh2ykscn7)" ...>
我尝试了很多方法,例如:
$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);
答案 0 :(得分:1)
有很多理由不使用正则表达式来解析HTML。相反,我们可以使用 DOM extension 。
要使用base64进行编码,我们将使用base64_encode()
。
<强>代码强>
$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;
<强>输出强>
<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>