preg_replace expression help needed for PHP
Trying to strip some BBCode from some text. I would like to remove everything between a [img] a开发者_如何学Pythonnd 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
will take care of everything between [img]
and [/img]
(case in-sensitive)
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" />'
精彩评论