strip_tags() function blacklist rather than whitelist

匿名 (未验证) 提交于 2019-12-03 01:54:01

问题:

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 = ''; $html = '

This should be bold

'; $html .= '

This is awesome

'; $html .= 'This should be bold'; echo strip_tags($html,"

");

returns this:

This should be bold

This is awesome

This should be bold

consequently I gotten rid of my formatting via and perhaps in the future.

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

echo blacklist_tags($html,""); 

returning:

This should be bold

This is awesome

This should be bold

Is there any way to do this?

回答1:

If you only wish to remove the tags, you can use DOMDocument instead of strip_tags().

$dom = new DOMDocument(); $dom->loadHTML($your_html_string);  // Find all the  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(); 


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!