如何使用php在文本中查找多个出现的标记?

如何使用php在文本中查找多个出现的标记?,php,find,preg-match,preg-match-all,Php,Find,Preg Match,Preg Match All,我有一个使用preg_match_all的简单php示例 $str = " Line 1: This is a string Line 2: [img] image_path [/img] Should not be [img] image_path2 [/img] included. Line 3: End of test [img] image_path3 [/img] string."; preg_match_all("~\[img](.+)\[/img]~i", $str, $

我有一个使用preg_match_all的简单php示例

$str = " 
Line 1: This is a string 
Line 2: [img] image_path [/img] Should not be [img] image_path2 [/img] included. 
Line 3: End of test [img] image_path3 [/img] string."; 

preg_match_all("~\[img](.+)\[/img]~i", $str, $m); 

var_dump($m);
我希望它能回来

array(
    [0] =>image_path
    [1] =>image_path2
    [2] =>image_path3
)
由于某种原因,我没有得到这个结果

蚂蚁创意?

将其更改为:

preg_match_all("~\[img](.+?)\[/img]~i", $str, $m); 

var_dump($m[1]);
您需要
的原因是使其“非贪婪”。使用您的代码,它将从第一个开始标记匹配到最后一个结束标记。默认情况下,
+
*
运算符是贪婪的,消耗尽可能多的字符。
修饰符停止此行为

您需要转储
$m[1]
而不是
$m
,因为
preg\u match*
也会匹配整个匹配字符串,而不仅仅是标记的捕获


实例:

不确定为什么标记用[]括起来,但如果您只是在寻找php html解析,请查看php。这看起来像BBCode,而不是html。但也有一个PHP扩展: