With preg_replace
and the \G
anchor:
echo preg_replace('~(?:\G(?!\A)|\bstart\b)[^e]*\K(?:\Be|e(?!nd\b))~S', '', $str);
details:
~
(?:
\G(?!\A) # contiguous to the previous match, not at the start of the string
| # OR
\bstart\b # the word "start"
)
[^e]* # all that is not an "e"
\K # exclude all previous matched characters from the whole match
(?:
\Be # an "e" that is not the start of a word
| # OR
e(?!nd\b) # an "e" that is not followed by "nd"
)
~
S # the STUDY modifier that tries to improve non-anchored patterns
This pattern find one "e" at a time. Once the word "start" is found, the \G
anchor forces the next match to be contiguous, since it matches the position at the end of the previous match. When the word "end" is reached (?:\Be|e(?!nd\b))
fails and the contiguity is broken (until an other eventual word "start").
Note that this pattern doesn't check if the word "end" exists in the string (but it can easily be done). If the word "end" doesn't exist, all "e" will be removed from the word "start" until the end of the string.