我有用户提交一些文本(包括随机HTML图像链接),然后我试图从文本中的图像创建一个基本的BBCode [img] [/ img]标签 .
我目前正在测试的方式是这样的:
字符串(取自随机论坛):
After a fair few years of doing the usual lowering, fitting wheels etc,when it comes to car modifying, we spent a couple of years doing Minimoto racing all round the country in the Southern British Minimoto Championship winning the 2006 Production Privateer Championship.
<img src="http://i2.photobucket.com/albums/y18/moo0484/scan0001.jpg" border="0" class="tcattdimglink" onload="NcodeImageResizer.createOn(this);" alt="" />
<img src="http://i2.photobucket.com/albums/y18/moo0484/01072007065.jpg" border="0" class="tcattdimglink" onload="NcodeImageResizer.createOn(this);" alt="" />
然后我替换任何图像属性/使用函数将图像标签更改为bbcode:
function convert($text) {
$text = preg_replace('/class=".*?"/', '', $text);
$text = preg_replace('/alt=".*?"/', '', $text);
$text = preg_replace('/src="/', '', $text);
$text = preg_replace('/border=".*?"/', '', $text);
$text = preg_replace('/onload=".*?"/', '', $text);
$text = str_replace("<img", "[img]", "$text");
$text = str_replace('">', "[/img]", "$text");
return nl2br($text);
}
如果标签未使用尾部斜杠关闭,则此工作完全正常 . 我可以添加另一个规则:
$text = str_replace('"/>', "[/img]", "$text");
哪个会起作用,但是还有一个空白区域,我从那里删除了属性 .
所以我的问题是,我可以从img标签之间删除空格:
<img />
例如,在preg_replace函数中 . *?替换“”之间的内容 .
我可以用img标签做类似的事情,并删除它们之间的空白区域吗?
我显然不能跑:
$text = preg_replace('/\s+/', '', $text);
因为我需要文本中的空格等 .
谢谢!
1 回答
您应该删除任何空格和rouge属性,以便所有属性,尤其是on *事件属性,如onClick,onBlur . 有很多方法可以将XSS攻击添加到HTML中 . 制作一些将它们全部删除的内容将无法维护,因此如果您想让用户输入HTML,请使用htmlpurifier . 它很容易初始化为您的代码,并有很多选项 .
一个简单的替代方法是只提取img的src然后删除属性并将src放回并创建一串图像,然后使用strip_tags()删除所有HTML,然后将图像连接到文本上 . 它缺乏图像的定位 .
So something like:
虽然只是考虑使用htmlpurifier,但1990年代也在呼吁他们希望BBCODE重新使用降价代替 . ,p
祝好运