0
0
PHPprogramming~5 mins

Lookahead and lookbehind in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a lookahead in regular expressions?
A lookahead checks if a certain pattern exists ahead in the text without including it in the match. It looks forward but does not consume characters.
Click to reveal answer
beginner
What is a lookbehind in regular expressions?
A lookbehind checks if a certain pattern exists behind the current position without including it in the match. It looks backward but does not consume characters.
Click to reveal answer
intermediate
How do you write a positive lookahead in PHP regex?
Use (?=pattern). For example, /foo(?=bar)/ matches 'foo' only if it is followed by 'bar'.
Click to reveal answer
intermediate
How do you write a negative lookbehind in PHP regex?
Use (?<!pattern). For example, /(?<!foo)bar/ matches 'bar' only if it is NOT preceded by 'foo'.
Click to reveal answer
intermediate
Why use lookahead and lookbehind instead of normal matching?
They let you check context around a match without including that context in the matched text. This helps when you want to find a pattern only if it is near another pattern, but you don't want to capture the nearby pattern.
Click to reveal answer
Which syntax represents a positive lookahead in PHP regex?
A(?<=pattern)
B(?=pattern)
C(?!pattern)
D(?<!pattern)
What does (?foo)bar match?
AMatches 'bar' only if NOT preceded by 'foo'
BMatches 'foo' followed by 'bar'
CMatches 'bar' only if preceded by 'foo'
DMatches 'bar' only if followed by 'foo'
Which lookaround checks text after the current position?
ANeither
BLookbehind
CBoth lookahead and lookbehind
DLookahead
What is the main difference between lookahead and normal matching?
ALookahead does not consume characters, normal matching does
BLookahead matches only digits
CLookahead matches only at the start of the string
DLookahead consumes characters in the match
Which of these is NOT a valid lookaround syntax in PHP regex?
A(?<!pattern)
B(?<=pattern)
C(?<>pattern)
D(?=pattern)
Explain how lookahead and lookbehind help in matching patterns with context in PHP regex.
Think about checking surroundings without including them in the match.
You got /4 concepts.
    Write a PHP regex example using positive lookahead and explain what it matches.
    Try matching a word only if followed by another word.
    You got /3 concepts.