获取[IMG]标签之间的匹配内容


Preg match contents between [IMG] tags

我正在编写一个脚本,用于检索帖子中的第一个图像链接

$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

我想只是返回"myhouse.png"并将其保存到一个变量中此外,img应该不区分大小写,这意味着它将适用于[img]text-here[/img][IMG]text-here[/IMG]

这将返回第一张图像:

$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

出现了一个正则表达式:

$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]);

解释:

正则表达式匹配一对[img] ... [/img]标记之间的所有内容。为了确保它不会匹配第一个[img]和最后一个[/img]标签之间的所有文本,我使用了不贪婪的修饰符。

了解PHP的正则表达式语法