开发者

How to remove consecutive links from a webpage?

开发者 https://www.devze.com 2023-03-29 15:56 出处:网络
I wish to remove consecutive links on a webpage Here is a sample <div style=\"font-family: Arial;\">

I wish to remove consecutive links on a webpage

Here is a sample

<div style="font-family: Arial;">
    <br>
    &nbsp;
    <a href="http://google.com">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</a>
    &nbsp;
    <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();
0

精彩评论

暂无评论...
验证码 换一张
取 消