匹配两个事物之间的字符串

Matching two things with string in between

我自己编写了一个语法,它适用于这样的事情:

$str = "abc {{for items}} efg";
preg_match('/(?<={{for )[^}]*(?=}})/', $str, $match);

// Returns: [0] => items

但我想将 for 命令扩展为这样工作:

$str = "abc {{for item in items}} efg";

如何修改正则表达式以匹配 "item" 和 "items" 并排除 "for" 和 "in" 部分?

我知道我可以这样做:

preg_match('/{{for (.*) in (.*)}}/', $str, $match);

但我喜欢我原来的正则表达式,因为它只有 returns 匹配的部分,所以我希望得到一些帮助来修改它以支持这个例子。

提前致谢!

编辑: 它并不总是{{for item in items}}也可能是{{for piece in products}}或{{for part in junk}}

我假设你的输入格式和上面的完全一样。

{{for\s+\K[^\s}]+(?=\s+in\s+[^\s}]+}})|[^\s}]+(?=}})

\K keeps the text matched so far out of the overall regex match. (?=...) 称为正先行断言。

DEMO