PHP 所需的 preg_replace 表达式帮助

发布于 2024-10-01 19:37:58 字数 300 浏览 2 评论 0原文

尝试从某些文本中删除一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

感情旳空白 2024-10-08 19:37:58

首先,找到与您的 BBCode 标记相匹配的模式:

\[img\][^\[]+\[/img\]

唯一困难的部分是类 [^\]]\[ 表示任何左括号,^ 表示 NOT。所以这个类将匹配除 [ 之外的所有内容。
您还可以用 .+ 替换该类并使用 U(不贪婪)选项。

现在您已经知道要使用哪种模式了,只需将其替换为...空字符串即可。工作完成了!

这是一个非常基本的正则表达式,理解它并且能够重现它很重要

First, find the pattern that would match your BBCode tag:

\[img\][^\[]+\[/img\]

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

躲猫猫 2024-10-08 19:37:58
/\[img\].*?\[\/img\]/i

将处理 [img][/img] 之间的所有内容(不区分大小写)

/\[img\].*?\[\/img\]/i

will take care of everything between [img] and [/img] (case in-sensitive)

oО清风挽发oО 2024-10-08 19:37:58

不要忘记对内容进行分组,例如 '/[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" />'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文