0

我希望能够查看字符串并找到所有出现的模式。如果您知道要发生多少次模式,这很容易用 preg_match 完成,但是当不知道出现次数时,我想不出一种方法来让它工作。

下面是一个已知事件集的有效查询示例:

$pattern = '/\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\]/';
$string = "[VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]";
preg_match ( $pattern , $string, $matches );

print_r ( $matches );

这将返回您期望的结果:

[0] => [VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]
[1] => one
[2] => two
[3] => three
[4] => four

我已经尝试了preg_matchpreg_match_all的不成功变体(使用和不使用 PREG_OFFSET_CAPTURE 参数):

$pattern = '/\[VAR:(.*)\]/';

任何帮助将不胜感激。

4

1 回答 1

0

它适用于以下模式和preg_match_all

$pattern = "/\[VAR:(.*?)\]/";

有关修改后的示例,请参见http://ideone.com/lGsHl

?之后.*使它不贪婪。

于 2012-09-29T21:29:33.303 回答