我想将HTML变量中的所有链接更改为随机链接。这是我的代码,但有一些阻止更改链接的方法:
<?php
$jobTemplateDetails = '<a href="https://www2.google.com">Click!</a>
<a href="https://www3.google.com">Click!</a>';
////////////////////// CHANGE ALL LINKS
$linkDom = new DOMDocument;
@$linkDom->loadHTML($jobTemplateDetails);
$allLinks = $linkDom->getElementsByTagName('a');
foreach ($allLinks as $rawLink) {
$longLink = $rawLink->getAttribute('href');
$str = 'abcdefghijklmnopqrstuvwxyz';
$randomChar1 = $str[mt_rand(0, strlen($str)-1)];
$randomChar2 = $str[mt_rand(0, strlen($str)-1)];
$randomChar3 = $str[mt_rand(0, strlen($str)-1)];
$randomChar4 = $str[mt_rand(0, strlen($str)-1)];
$shortURL = mt_rand(1, 9).$randomChar1.mt_rand(1, 9).$randomChar2.$randomChar3.$randomChar4;
$rawLink->setAttribute('href', $shortURL);
}
echo $jobTemplateDetails;
答案 0 :(得分:1)
echo $jobTemplateDetails;
时,仅显示第一个输入字符串,而不显示您操作的DomDocument。
将其更改为
echo $linkDom->saveHTML();
///OUTPUT:
<a href="7y2rpn">Click!</a>
<a href="3b5qtr">Click!</a>