user2263996
user2263996

Reputation: 47

Preg match contents between [IMG] tags

I'm writing a script that retrieves the first image link in a post

$content = [center]Hello World, this is my house: [img]myhouse.png[/img] blah blah blah blah [/center] This is another house [img]anotherhouse.png[/img] , blah blah blah

I would like to just return "myhouse.png" and save it into a variable Also img should be case insensitive, meaning it would work on [img]text-here[/img] or [IMG]text-here[/IMG]

Upvotes: 1

Views: 198

Answers (2)

hek2mgl
hek2mgl

Reputation: 157992

Here comes a regex:

$content = '[center]Hello World, this is my house: [img]myhouse.png[/img] blah blah blah blah [/center] This is another house [img]anotherhouse.png[/img] , blah blah blah';

$pattern = '/\[img\](.*)\[\/img\]/U'; // <-- the U means ungreedy

preg_match_all($pattern, $content, $matches);
var_dump($matches[1]);

Explanation:

The regex matches everything between a pair of [img] ... [/img] tags. To make sure that it will not match all text between the first [img] and the last [/img] tag I've use the ungreedy modifier.

Learn more about PHP's regex syntax.

Upvotes: 1

HamZa
HamZa

Reputation: 14921

This will return the first image:

$content = '[center]Hello World, this is my house: [img]myhouse.png[/img] blah blah blah blah [/center] This is another house [img]anotherhouse.png[/img] , blah blah blah';

preg_match('#\[img\]\s*(?P<png>.*?)\s*\[/img\]#i', $content, $m);
echo $m['png']; // myhouse.png

Upvotes: 1

Related Questions