Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape certain html tags in a string

Tags:

php

I need to escape all html tags but with some exception like: <b>, <font> etc

For example:

 Hello <b>world</b>. How are <span>you</span>?

Will result in: Hello world. How are you <span>you</span>

like image 468
keepwalking Avatar asked Mar 23 '11 09:03

keepwalking


2 Answers

In my experience, the best way to manipulate certain HTML tags in my experience is to use a DOM parser like HTML purifier, however this can be a bit tricky to setup and even a bit overkill for your application. If I was to do it all again I would use a different format (like wiki format, or bb code) and not HTML, that way you can convert your own, simple tags to HTML and you have full control over the output.

Back to the question in hand, A quick solution for you would be to use strip_tags() and pass a second argument of a tag whitelist - although this isn't 100% perfect/safe for out putting HTML, so in the long run you should use either a DOM parser or not permit HTML input.

like image 110
Dunhamzzz Avatar answered Nov 18 '22 22:11

Dunhamzzz


Use http://htmlpurifier.org

I'd also take a look at http://htmlpurifier.org/comparison

like image 33
Peeter Avatar answered Nov 18 '22 21:11

Peeter