简体   繁体   中英

preg_replace expression help needed for PHP

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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