PHP Getting and Setting tag attributes

前端 未结 2 1348
天涯浪人
天涯浪人 2021-01-28 15:50

im being played by php and DomDocument.... basically i have some html saved in db. With anchor tags with different urls.... i want to force anchor tag hrefs not within allowedur

2条回答
  •  悲&欢浪女
    2021-01-28 16:19

    This should be pretty straight-forward.

    First, let's grab all of the anchor tags. $doc is the document you've created with your HTML as the source.

    $anchors = $doc->getElementsByTagName('a');
    

    Now we'll go through them one-by-one and inspect the href attribute. Let's pretend that the function contains_bad_url returns true when the passed string is on your blacklist. You'll need to write that yourself.

    foreach($anchors as $anchor)
        if($anchor->hasAttribute('href') && contains_bad_url($anchor->getAttribute('href'))) {
            $anchor->setAttribute('href', '#');
        }
    }
    

    Tada. That should be all there is to it. You should be able to get the results back as an XML string and do whatever you need to do with the rest.

提交回复
热议问题