PHP Getting and Setting tag attributes

前端 未结 2 1374
天涯浪人
天涯浪人 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:33

    Thanx Charles.... came up with this

    function contains_bad_urls($href,$allowed_urls)
    {
        $x=pathinfo($href);
        $bn=$x['filename'];
        if (array_search($bn,$allowed_urls)>-1)
        {
            return false;
        }   
        return true;
    }
    
    function CleanHtmlUrls($str)
    {
        $allow_urls = array('viewprofile','viewwall');//change these to whatever filename
        $doc = new DOMDocument();
        $doc->loadHTML($str);
        $doc->formatOutput = true;
        $anchors = $doc->getElementsByTagName('a');
        foreach($anchors as $anchor)
        {
        $anchor->setAttribute('onclick','#');
            if(contains_bad_urls($anchor->getAttribute('href'),$allow_urls)) 
            {
                $anchor->setAttribute('href', '#');
            }
        }
        $ret=$doc->saveHTML();
        return $ret
    }   
    

提交回复
热议问题