Strip_tags () is a blacklist, not a whitelist

I recently discovered a strip_tags() function that takes a string and a list of accepted html tags as parameters.

Suppose I wanted to get rid of the images in a row, here is an example:

 $html = '<img src="example.png">'; $html = '<p><strong>This should be bold</strong></p>'; $html .= '<p>This is awesome</p>'; $html .= '<strong>This should be bold</strong>'; echo strip_tags($html,"<p>"); 

returns this:

 <p>This should be bold</p> <p>This is awesome</p> This should be bold 

therefore, I got rid of my formatting through <strong> and possibly <em> in the future.

I want to use a blacklist, not a whitelist:

 echo blacklist_tags($html,"<img>"); 

return:

 <p><strong>This should be bold<strong></p> <p>This is awesome</p> <strong>This should be bold<strong> 

Is there any way to do this?

+6
source share
2 answers

If you want to remove the <img> tags, you can use DOMDocument instead of strip_tags() .

 $dom = new DOMDocument(); $dom->loadHTML($your_html_string); // Find all the <img> tags $imgs = $dom->getElementsByTagName("img"); // And remove them $imgs_remove = array(); foreach ($imgs as $img) { $imgs_remove[] = $img; } foreach ($imgs_remove as $i) { $i->parentNode->removeChild($i); } $output = $dom->saveHTML(); 
+7
source

You can do this by writing a special function. Strip_tags () is considered more secure though, since you can forget the blacklist of some tags ...

PS: Some examples of functions can be found in the comments on the php.net strip_tags () page.

+1
source

Source: https://habr.com/ru/post/895106/


All Articles