PHP 所需的 preg_replace 表达式帮助
尝试从某些文本中删除一些 BBCode。我想使用 PHP preg_replace 函数删除 [img] 和 [/img] 之间的所有内容,例如:
Here is my image[img]http://www.abc.com/image1.jpg[/img] and more text
Match: [img] 后跟任意数量的字符,后跟 [/img]
结果:
Here is my image and more text
谢谢。
Trying to strip some BBCode from some text. I would like to remove everything between a [img] and a [/img], using a PHP preg_replace function, for example:
Here is my image[img]http://www.abc.com/image1.jpg[/img] and more text
Match: [img] followed by any number of characters followed by [/img]
Result:
Here is my image and more text
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,找到与您的 BBCode 标记相匹配的模式:
唯一困难的部分是类
[^\]]
。\[
表示任何左括号,^ 表示 NOT。所以这个类将匹配除[
之外的所有内容。您还可以用
.+
替换该类并使用 U(不贪婪)选项。现在您已经知道要使用哪种模式了,只需将其替换为...空字符串即可。工作完成了!
这是一个非常基本的正则表达式,理解它并且能够重现它很重要
First, find the pattern that would match your BBCode tag:
The only hard part is the class
[^\]]
. The\[
means any opening bracket and the ^ means NOT. So this class will match everything that is not a[
.You could also replace the class with
.+
and use the U (ungreedy) option.Now that you now which pattern to use, you just have to replace it with... an empty string. And the job is done!
This is a very basic regexp, it's important that you understand it and that you are able to reproduce it
将处理
[img]
和[/img]
之间的所有内容(不区分大小写)will take care of everything between
[img]
and[/img]
(case in-sensitive)不要忘记对内容进行分组,例如 '/[img](.+)[\/img]/i',因此在替换条件下,您可以引用标签 ''
don't forget to group your content e.g. '/[img](.+)[\/img]/i', so in you replace condition you can reference the value between the tags '<img src="$1" />'