简体   繁体   中英

Remove all style attributes from HTML in PHP

I have to load the body of an HTML page without any style attribute and no link images and everything that is not 'plain text. I would like to do it in PHP and tried very solution but I have not solved. I load the html page with an ajax call to my script and then with a regular expression I take the body that then I want this cleared. Can you help me? This is the ajax call:

$.ajax({
       type: "GET"
       url: "core/proxy.php?url="+cerca,              
       success: function(data){
       var body = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
       .replace(/<\/body[\S\s]*$/i, "");
        $("div#risultato").html(body);
    },
      error: function(){
      alert("failed");
    }
    });
});

You could use jQuery to just get the text content of the body .

So, in your success function, you would take the data , convert it to a jQuery-object and insert the text in your div.

$('div#risultato').html($(data).find('body').text());

You could clear style attributes, tag by tag, after insert the body :

function clearStyles(element) {
    element.setAttribute('style', '');
    for (var i = 0; i < element.children.length; i++) {
        clearStyles(element.children[i]);
    }
}

clearStyles(document.body);

http://jsfiddle.net/n9ocxa0g/

Or directly with jQuery:

jQuery('body *').attr('style', '');

Jose Antonio Riaza Valverde I corrected but nothing changes:

$.ajax({
            //definisco il tipo della chiamata
            type: "GET",
            //url della risorsa da contattare
            url: "core/proxy.php?url="+cerca,
            //azione in caso di successo
            success: function(data)
            {
                var body = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
                .replace(/<\/body[\S\s]*$/i, "");
                $("div#risultato").html(body);
                clearStyles(document.getElementById('risultato'));

            },
            //azione in caso di errore
            error: function()
            {
                alert("Chiamata fallita");
            }
    });
});

and the function:

function clearStyles(element) {
element.setAttribute('style', ' ');
element.setAttribute('img', ' ');
element.setAttribute('a', ' ');
for (var i = 0; i < element.children.length; i++) {
    clearStyles(element.children[i]);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM