简体   繁体   English

PHP需要preg_replace表达式帮助

[英]preg_replace expression help needed for PHP

Trying to strip some BBCode from some text. 试图从某些文本中剥离一些BBCode。 I would like to remove everything between a [img] and a [/img], using a PHP preg_replace function, for example: 我想使用PHP preg_replace函数删除[img]和[/ img]之间的所有内容,例如:

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] 匹配:[img],后跟任意数量的字符,后跟[/ img]

Result: 结果:

Here is my image and more text

Thanks. 谢谢。

First, find the pattern that would match your BBCode tag: 首先,找到与您的BBCode标签匹配的模式:

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

The only hard part is the class [^\\]] . 唯一困难的部分是类[^\\]] The \\[ means any opening bracket and the ^ means NOT. \\[表示任何左括号,^表示NOT。 So this class will match everything that is not a [ . 因此,此类将匹配所有非[
You could also replace the class with .+ and use the U (ungreedy) option. 您也可以将类替换为.+并使用U(ungreedy)选项。

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\]/i

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

不要忘记对内容进行分组,例如'/[img](.+)[\\/img]/i',因此在替换条件时,您可以引用标签'<img src =“ $ 1” />之间的值'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM