You can use two lookarounds and the /s
(single line) modifier, which makes the dot match newlines, to look for everything between your two words:
/(?<=test).*(?=end)/s
To explain:
(?<= # open a positive lookbehind
test # match 'test'
) # close the lookbehind
.* # match as many characters as possible (including newlines because of the \s modifier)
(?= # open a positive lookahead
end # match 'end'
) # close the lookahead
The lookarounds will let you assert that the pattern must be anchored by your two words, but since lookarounds are not capturing, only everything between the words will be returned by preg_match
. A lookbehind looks behind the current position to see if the assertion passes; a lookahead looks after the current position.
Since regular expressions are greedy by default, the .*
will match as much as it can (so if the ending word appears multiple times, it will match until the last one). If you want to match only until the first time it encounters end
, you can make the .*
lazy (in other words, it'll match as little as possible that still satisfies the pattern) by changing it to .*?
(ie. /(?<=test).*?(?=end)/s
).