开发者

Escape certain html tags in a string

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>


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.


Use http://htmlpurifier.org

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


It needs a simple logic to implement, something like below:
1. Create a list of html tags which you DON't want to escape.
2. Intercept an html tag (opening or closing).
3. If the tag is not present in your list, replace the surrounding angle brackets (<>) with &lt; and &gt;, i.e. <mytag> becomes &lt; mytag &gt;
4. Repeate this for all the tags in your html file.


php has a function strip_tags, i think it will be exactly what you are looking for here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜