Other way: force the pattern to fail and to not retry if world
doesn't exist in the string:
~(?:\A(*COMMIT).*?world)?.*?hello~s
demo
The non-capturing group is optional but greedy. Consequence, it is tested each time the pattern is tried.
It begins with the \A
anchor that matches the start of the string, so this is the only position where this group can succeed. After the start of the string, at other positions \A
fails and since the group is optional, the remaining subpattern in it is ignored and the research continues with .*?hello
.
Immediately after, there's the backtracking control verb (*COMMIT)
that in case of failure after it, forces the pattern to not be retried at all. (end of the story).
In other words, if this group fails at the start of the string, the research is aborted once and for all.
Advantage: it needs less steps than a \G
based pattern.
To be more efficient, a \G
based pattern can also be written this way (using an optional group instead of an alternation):
~(?:\A.*?world)?(?!\A).*?hello~sA
Here the A modifier takes the role of the \G
anchor, but it's exactly the same than starting each branch of a pattern (only one here) with the \G
anchor.