Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strip_tags() function blacklist rather than whitelist

Tags:

php

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

Lets say I wanted to get rid of images in a string 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

consequently I gotten rid of my formatting via <strong> and perhaps <em> in the future.

I want a way to blacklist rather than whitelist something like:

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

returning:

<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?

like image 557
ThomasReggi Avatar asked Aug 16 '11 00:08

ThomasReggi


2 Answers

If you only wish 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();
like image 124
Michael Berkowski Avatar answered Sep 28 '22 07:09

Michael Berkowski


You can only do this by writing a custom function. Strip_tags() is considered more secure though, because you might forget to blacklist some tags...

PS: Some example functions can be found in the comments on php.net's strip_tags() page

like image 42
mcls Avatar answered Sep 28 '22 09:09

mcls