Reputation: 2214
I have made a syntax of my own and it works fine for things like this:
$str = "abc {{for items}} efg";
preg_match('/(?<={{for )[^}]*(?=}})/', $str, $match);
// Returns: [0] => items
But I want to expand the for command to work like this:
$str = "abc {{for item in items}} efg";
How do I need to modify the regexp to match the "item" and "items" and exclude the "for" and "in" parts?
I am aware that I could do it like this:
preg_match('/{{for (.*) in (.*)}}/', $str, $match);
But I like my original regexp because it only returns the matched parts so I would like to have some help modifying it to support this example.
Thanks in advance!
EDIT: It's not always {{for item in items}} it might aswell be {{for piece in products}} or {{for part in junk}}
Upvotes: 0
Views: 43
Reputation: 174696
I assume that your input formats are exactly like above.
{{for\s+\K[^\s}]+(?=\s+in\s+[^\s}]+}})|[^\s}]+(?=}})
\K keeps the text matched so far out of the overall regex match. (?=...)
called positive lookahead assertion.
Upvotes: 1