Table of Contents
📖 1 minute read
Need to validate that a string contains multiple words in any order? Don’t write 6 permutations of the same regex. Use positive lookaheads instead.
The Problem
You want to check if a string contains “cat” AND “dog” AND “bird” in any order. The naive approach is a mess of permutations — 6 for 3 words, 24 for 4 words. No thanks.
The Fix: Chained Positive Lookaheads
$pattern = '/^(?=.*cat)(?=.*dog)(?=.*bird)/';
$text = 'I saw a bird, then a cat, then a dog';
if (preg_match($pattern, $text)) {
echo 'All three words found!';
}
Each (?=.*word) is a separate assertion. All must pass. Order doesn’t matter. Add a fourth word? Add one more lookahead. Clean and scalable.
Takeaway
Positive lookaheads let you check multiple conditions without caring about order. Use (?=.*word) for each required word. Works in PHP, JavaScript, Python — basically everywhere.

Leave a Reply