【发布时间】:2014-05-14 21:42:35
【问题描述】:
我让用户提交了一些文本(包括随机的 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.<br />
<br />
<img src="http://i2.photobucket.com/albums/y18/moo0484/scan0001.jpg" border="0" class="tcattdimglink" onload="NcodeImageResizer.createOn(this);" alt="" /><br />
<br />
<img src="http://i2.photobucket.com/albums/y18/moo0484/01072007065.jpg" border="0" class="tcattdimglink" onload="NcodeImageResizer.createOn(this);" alt="" /><br />
然后我使用函数替换任何图像属性/将图像标签更改为 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);
因为我需要文本中的空白等。
谢谢!
【问题讨论】:
-
您似乎正在尝试将正则表达式与
str_replace一起使用。你必须使用preg_replace。 -
刚刚改回来,之前使用的是 preg_replace 但决定将其更改为 str... 现在回到 preg 谢谢!
-
sidenote 你应该通过htmlpurifier 运行 html,在进行 bbcode 对话之前,你应该使用像 DOMDocument 这样的适当的 HTML 解析器来只提取你想要的东西,或者你会让你的访客接触到各种细菌!
-
暂时下载htmlpurifier。关于从文本的两个指定部分之间删除空格的任何想法?
标签: php html image preg-replace str-replace