I wish to remove consecutive links on a webpage
Here is a sample
<div style="font-family: Arial;">
<br>
<a href="http://google.com">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</a>
<a hre开发者_StackOverflow社区f="http://google.com">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB</a>
Google is a search
<a href="http://www.google.com">engine</a>
In the above html I want to remove the first 2 A tags and not the third one (My script should only remove consecutive tags)
Don't use a regex for this. They are extremely powerful but not for finding this kind of "consecutive" tags.
I suggest you use DOM. Then you can browse the HTML as a tree. Here is an example (not tested):
$doc = new DOMDocument();
// avoid blank nodes when parsing
$doc->preserveWhiteSpace = false;
// reads HTML in a string, loadHtmlFile() also exists
$doc->loadHTML($html);
// find all "a" tags
$links = $doc->getElementsByTagName('a');
// remove the first link
$parent = $links->item(0)->parentNode;
$parent->removeChild($links->item(0));
// test the node following the second link
if ($links->item(1)->nextSibling->nodeType != XML_TEXT_NODE) {
// delete this node ...
}
// print the modified HTML
// See DOMDocument's attributes if you want to format the output
echo $doc->saveHTML();
精彩评论