简体   繁体   English

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

[英]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] 我只想返回“ myhouse.png”并将其保存到变量中img应该不区分大小写,这意味着它可以在[img]text-here[/img][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. 正则表达式匹配一对[img] ... [/img]标签之间的所有内容。 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. 为了确保它不匹配第一个[img]和最后一个[/ img]标签之间的所有文本,我使用了ungreedy修饰符。

Learn more about PHP's regex syntax. 了解有关PHP的正则表达式语法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM