简体   繁体   中英

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]

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

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.

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