我如何使用PHP在白名单中允许使用HTML [英] How can I allow HTML in a whitelist with PHP

查看:314
本文介绍了我如何使用PHP在白名单中允许使用HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多年来关于用PHP过滤数据的最佳方法的讨论,但是我想在当前的项目中使用白名单方法。



我只希望用户能够使用以下HTML

 < b>加粗< / b> 
< i>斜体< / i>
< u>下划线< / u>
< s>删除线< / s>
< big>大尺寸< / big>
< small>小尺寸< / small>

超连结< a href =http://www.site.com>网站< / a>

项目符号清单:
< ul>
< li>单个项目< / li>
< li>另一项目< / li>
< / ul>

有序清单:


    < li>第一项< / li>
    < li>第二项< / li>
    < / ol>

    < blockquote>因为它被缩进< / blockquote>

    < h1>标题1< / h1>
    < h2>标题2< / h2>
    < h3>标题3< / h3>

任何人都可以看到在PHP中执行此操作的最佳方法吗?我只有在过去允许所有的HTML减去某些代码

解决方案

最简单的解决方案将是 strip_tags ),它接受包含允许标记的第二个参数:

  strip_tags($ string,< b个;< I>< U>< a取代;< S取代;<大><小>< UL><李><醇>< BLOCKQUOTE>< H1>< H2> < H3>中); 


I know there is a lot of discussion for years on best methods of filtering data with PHP but I would like to go the whitelist approach in my current project.

I only want a user to be able to use the following HTML

<b>bold</b>
<i>italics</i>
<u>underline</u>
<s>strikethrough</s>
<big>Big size</big >
<small>Small size</small>

Hyperlink <a href="http://www.site.com">website</a>

A Bulleted List:
<ul>
<li>One Item</li>
<li>Another Item</li>
</ul>

An Ordered List:
<ol>
<li> First Item</li>
<li> Second Item</li>
</ol>

<blockquote>Because it is indented</blockquote>

<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>

Can anyone show me the best method of doing this for performance in PHP? I have only in the past allowed all html minus certain codes

解决方案

The simplest solution would be strip_tags(), which accepts a second argument containing allowable tags:

strip_tags($string, "<b><i><u><a><s><big><small><ul><li><ol><blockquote><h1><h2><h3>");

这篇关于我如何使用PHP在白名单中允许使用HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆