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?
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With