我试图完全消除某些<a>
标签,但将文本和原始href保留在分类的<span>
标签中。
之前:<a href="www.example.com">Click here</a>
之后: <span class="myClass" data-href="www.example.com">Click Here</span>
我设法用下面的代码替换了纯文本的链接,但是得知我不能包含任何标记。我该如何修改代码以从上方完成之前/之后?
$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($output);
$domx = new DOMXPath($domd);
foreach ($domx->query("//a") as $link) {
$href = $link->getAttribute("href");
if (strpos($href, 'oursite.com') === false) {
continue; // Don't change links to our site.
}
$text = $domd->createTextNode($link->nodeValue);
$link->parentNode->replaceChild($text, $link);
}
答案 0 :(得分:2)
您可以做什么:
$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($output);
$domx = new DOMXPath($domd);
foreach ($domx->query("//a") as $link) {
$href = $link->getAttribute("href");
// by the way, it should be NOT false to skip your urls
if (strpos($href, 'oursite.com') !== false) {
continue; // Don't change links to our site.
}
// create span-element
$span = $domd->createElement('span', $link->nodeValue);
// set span attributes
$span->setAttribute('class', "myClass");
$span->setAttribute('data-href', $href);
// replace $link with $span
$link->parentNode->replaceChild($span, $link);
}