سؤال

I have a BBCode like this.

[IMG]art_74e7e4f8811380426577.jpeg[/IMG] [IMG]art_74e7e4f8811380426595.jpeg[TITLE]title is always needy[/TITLE][/IMG]

I need to extract the two images. So my preg_match_all is:

preg_match_all('/\[IMG\][^(\[\/IMG\])]+/', $body, $matches);

Which gives me this:

[0] => [IMG]art_74e7e4f8811380426577.jpeg

[1] => [IMG]art_74e7e4f8811380426595.jpeg

I need to include the title tag into the second occurence. Really stuck...

هل كانت مفيدة؟

المحلول

Use this to get the image tags as well:

preg_match_all('~\[img\].*?\[/img\]~i', $body, $matches);

regex101 demo

The i modifier is for case insensitive matching.

If you don't want to get the image tags, use lookarounds:

preg_match_all('~(?<=\[img\]).*?(?=\[/img\])~i', $body, $matches);

By the way: [^(\[\/IMG\])]+ will match any character except (, [, /, I, M, G, ], )

regex101 demo

(?<=\[img\]) is a positive lookbehind and makes sure your match has [img] before it and

(?=\[/img\]) is a positive lookahead which makes sure your match has [/img] after it. Those don't count as matches so they won't be returned in your capture group.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top