0

I don't want to use htmlentities() because I just want to strip 3 kinds of tags and allow all others. These are the ones to be stripped:

- <a hrefs...
- <scripts...
- <img src...

How can this be done?

1
  • You sure you want to allow all others? What's your actual reason for wanting to remove these ones?
    – David
    Mar 17, 2011 at 0:54

2 Answers 2

3
$str = strip_tags($str, '<a><script><img>');

However, if this is for security, this is not enough. Use a HTML parser and a whitelist of allowed tags and attributes.

Otherwise I may enter <button onclick="alert('xss')">hello!</button>, for example.

3
  • 1
    I would second the "this is not enough" comment since if you allow people to post html they can add a "onmouseover" attribute to any tag. For example, even if you only allowed the <strong> tag I can do <strong style="width:100%;height:100%;position:absolute" onmouseover="alert('xss');">...</strong> and this will execute anytime the mouse is moved over the page.
    – JustJohn
    Mar 17, 2011 at 1:33
  • @JustJohn Just another reason to use a whitelist and parser. I chose the obvious HTML sample to point it out :P
    – alex
    Mar 17, 2011 at 1:46
  • 1
    indeed. Or ditch html altogether and use something like markdown or bbcode run through a well developed library with XSS protection.
    – JustJohn
    Mar 17, 2011 at 2:28
1

Check out php's strip_tags(). The optional parameter allows you to select allowable tags, which I know is the opposite of what you want to, but is the better way to go.

The other option is to use regular expressions to remove those offending tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.