<?php
$dom = new DOMDocument();
$dom->loadHtml('
<a href="http://example.com/books/1">The Lord of the Rings</a>
<ul>
<li><a href="http://example.com/books/1#c1" >Chapter 1</a></li>
<li><a name="name before href" href="http://example.com/books/1#c2">Chapter 2</a></li>
<li><a href="http://example.com/books/1#c3" name="name after href">Chapter 3</a></li>
<li><a href="http://example.com/books/1#cN" target="_blank">Chapter N</a></li>
</ul>
<br><br>
<a href="http://example.com/books/1">Harry Potter</a>
<ul>
<li><a href="http://example.com/books/2#c1" target="_self">Chapter 1</a></li>
<li><a href="http://example.com/books/2#c2" name="some have name" title="some others have title" >Chapter 2</a></li>
<li><a href="http://example.com/books/2#c3">Chapter 3</a></li>
<li><a href="http://example.com/books/2#cN" >Chapter N</a></li>
</ul>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//a") as $link) {
$href = $link->getAttribute('href');
if (strpos($href, '#') !== false) {
$link->parentNode->nodeValue = $link->nodeValue;
}
}
echo $dom->saveHTML();
- Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1
- <a href="http://example.com/books/1">The Lord of the Rings<ul>
<li>Chapter 1</li>
<li>Chapter 2</li>
<li>Chapter 3</li>
<li>Chapter N</li>
</ul><br><br><a href="http://example.com/books/1">Harry Potter</a><ul>
<li>Chapter 1</li>
<li>Chapter 2</li>
<li>Chapter 3</li>
<li>Chapter N</li>
</ul></a>
preferences:
82.49 ms | 408 KiB | 5 Q