Martin AJ Martin AJ - 1 year ago 105
HTML Question

How can I strip html tags except some of them?

I need to remove all html codes from a php string except:


You know, strip_tags() function is good, but it strips all html tags, how can I tell it remove all html except those tags above?

Jan Jan
Answer Source

According to your comment, you want to remove HTML elements only if they have some class or attribute. You'll need to build up a DOM then:


$data = <<<DATA
    <p>These line shall stay</p>
    <p class="myclass">Remove this one</p>
    <p><a href="#somewhere">I will be deleted as well</a></p>
    <p>But keep this</p>

$dom = new DOMDOcument();
$dom->loadHTML("<div id='wrapper'>".$data."</div>");

$xpath = new DOMXPath($dom);

$elements_to_be_removed = $xpath->query("//*[count(@*)>0]");
foreach ($elements_to_be_removed as $element) {

// just to check
echo $dom->saveHTML($dom->getElementById('wrapper'));

To change which elements shall be removed, you'll need to change the query, ie to remove all elements with the class myclass, it must read "//*[class='myclass']".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download