Bird
Raised Fist0
PHPprogramming~10 mins

Lookahead and lookbehind in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Lookahead and lookbehind
Start regex engine
↓
Check lookbehind condition
Yes↓
Match main pattern
↓
Check lookahead condition
Yes↓
Accept or reject match
The regex engine first checks the lookbehind condition before the main pattern, then matches the main pattern, and finally checks the lookahead condition after the main pattern to decide if the match is accepted.
Execution Sample
PHP
<?php
$pattern = '/(?<=\$)\d+(?=\sUSD)/';
$text = 'The price is $100 USD.';
preg_match($pattern, $text, $matches);
echo $matches[0];
?>
This code finds a number preceded by '$' and followed by ' USD' in the text.
Execution Table
StepActionText PositionCondition CheckedResultMatch Found
1Check lookbehind (?<=\$)Before '1' in '100'Is previous char '$'?YesContinue
2Match main pattern \d+At '100'Match digitsMatches '100'Continue
3Check lookahead (?=\sUSD)After '100'Is next chars ' USD'?YesAccept match '100'
4End---Match accepted: '100'
💡 Lookbehind and lookahead conditions met, so '100' is matched.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
matches[][]['100']['100']['100']
Key Moments - 2 Insights
Why does the regex check the lookbehind before matching digits?
Because lookbehind ensures the pattern before the main match is correct without consuming characters, as shown in step 1 of the execution_table.
What happens if the lookahead condition fails?
The match is rejected even if the main pattern matches, as the lookahead must confirm the following characters, shown in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is checked at Step 1?
AIf the next characters are digits
BIf the previous character is '$'
CIf the main pattern matches digits
DIf the following characters are ' USD'
💡 Hint
Check the 'Condition Checked' column at Step 1 in execution_table.
At which step does the regex confirm the main digits '100'?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Match Found' column to see when digits are matched.
If the text was 'The price is 100 USD.' (no '$'), what would happen at Step 1?
ALookbehind check passes
BMain pattern matches anyway
CLookbehind check fails, no match
DLookahead check fails
💡 Hint
Look at Step 1 condition about previous character being '$' in execution_table.
Concept Snapshot
Lookbehind (?<=...) checks text before the match without consuming it.
Lookahead (?=...) checks text after the match without consuming it.
Both are zero-width assertions.
Used to match patterns only if preceded or followed by specific text.
In PHP, use preg_match with these in regex patterns.
Full Transcript
This example shows how PHP regex uses lookbehind and lookahead. The regex pattern '/(?<=\$)\d+(?=\sUSD)/' looks for digits preceded by a dollar sign and followed by a space and 'USD'. The engine first checks the lookbehind condition before matching digits, then matches the digits, and finally checks the lookahead condition. If all conditions pass, the match is accepted. Variables track the matched results. Common confusions include why lookbehind is checked first and what happens if lookahead fails. The visual quiz tests understanding of these steps.

Practice

(1/5)
1. What does a positive lookahead (?=pattern) do in PHP regular expressions?
easy
A. Matches the pattern and consumes it in the string
B. Checks if the specified pattern precedes the current position and includes it in the match
C. Checks if the specified pattern follows the current position without including it in the match
D. Checks if the pattern is anywhere in the string regardless of position

Solution

  1. Step 1: Understand lookahead behavior

    A positive lookahead (?=pattern) checks if the pattern appears immediately after the current position without consuming characters.
  2. Step 2: Compare options with definition

    Checks if the specified pattern follows the current position without including it in the match correctly describes this behavior. Options B and C incorrectly describe lookbehind or normal matching. Checks if the pattern is anywhere in the string regardless of position is too broad.
  3. Final Answer:

    Checks if the specified pattern follows the current position without including it in the match -> Option C
  4. Quick Check:

    Positive lookahead = check after position [OK]
Hint: Lookahead checks after current spot without consuming [OK]
Common Mistakes:
  • Confusing lookahead with lookbehind
  • Thinking lookahead consumes characters
  • Assuming it matches anywhere, not just after position
2. Which of the following is the correct syntax for a negative lookbehind in PHP regex?
easy
A. (?pattern)
B. (?<=pattern)
C. (?!pattern)
D. (?=pattern)

Solution

  1. Step 1: Recall lookbehind syntax

    Negative lookbehind in PHP regex is written as (?<!pattern), which asserts that the pattern does NOT appear before the current position.
  2. Step 2: Match options to syntax

    (?
  3. Final Answer:

    (?<!pattern) -> Option A
  4. Quick Check:

    Negative lookbehind = (?<!pattern) [OK]
Hint: Lookbehind uses (?<=) or (?), negative has exclamation [OK]
Common Mistakes:
  • Mixing lookahead and lookbehind syntax
  • Using wrong brackets or missing exclamation mark
  • Confusing negative and positive forms
3. What will be the output of this PHP code?
$text = "apple pie";
if (preg_match('/apple(?= pie)/', $text)) {
    echo "Match found";
} else {
    echo "No match";
}
medium
A. Empty output
B. Match found
C. Syntax error
D. No match

Solution

  1. Step 1: Understand the regex pattern

    The pattern /apple(?= pie)/ matches 'apple' only if it is immediately followed by ' pie' without including ' pie' in the match.
  2. Step 2: Check the input string

    The string is "apple pie", so 'apple' is followed by ' pie'. The lookahead condition is true, so the match succeeds.
  3. Final Answer:

    Match found -> Option B
  4. Quick Check:

    Lookahead confirms 'apple' before ' pie' = Match found [OK]
Hint: Lookahead checks next chars without consuming [OK]
Common Mistakes:
  • Thinking lookahead consumes characters
  • Assuming no match because ' pie' is not part of match
  • Confusing output with syntax error
4. Identify the error in this PHP regex using lookbehind:
$text = "hello world";
if (preg_match('/(?
medium
A. No error, code runs fine
B. Lookbehind syntax is incorrect, missing brackets
C. Lookbehind must be at the end of the pattern
D. Lookbehind pattern is fixed width but 'hello' is variable length

Solution

  1. Step 1: Check lookbehind syntax and pattern

    The lookbehind (?<!hello) is valid because 'hello' is fixed length (5 characters), which PHP supports.
  2. Step 2: Analyze the string and pattern match

    The string is "hello world". The lookbehind asserts 'world' is NOT preceded by 'hello'. Here, 'world' is preceded by 'hello', so the match fails and "No match" is printed.
  3. Final Answer:

    No error, code runs fine -> Option A
  4. Quick Check:

    Lookbehind syntax correct, no error [OK]
Hint: Lookbehind must be fixed width, 'hello' is fixed length [OK]
Common Mistakes:
  • Thinking 'hello' is variable length
  • Assuming lookbehind syntax is wrong
  • Expecting match when lookbehind condition fails
5. You want to match all occurrences of the word 'cat' only if it is NOT preceded by 'wild' and is immediately followed by 's' in a string. Which regex pattern correctly uses lookahead and lookbehind in PHP?
hard
A. /(?<=wild )cat(?=s)/
B. /(?<=wild)cat(?=s)/
C. /(?wild)cat(?= s)/
D. /(?wild )cat(?=s)/

Solution

  1. Step 1: Understand the requirements

    We want 'cat' that is NOT preceded by 'wild ' (note the space) and IS followed immediately by 's'.
  2. Step 2: Analyze each option

    /(?(?<!wild ) to exclude 'wild ' before 'cat' and positive lookahead (?=s) to ensure 'cat' is followed by 's'. This matches the requirement.
    /(?<=wild )cat(?=s)/ uses positive lookbehind, which requires 'wild ' before 'cat', opposite of requirement.
    /(?/(?<=wild)cat(?=s)/ uses positive lookbehind without space, which is incorrect.
  3. Final Answer:

    /(?<!wild )cat(?=s)/ -> Option D
  4. Quick Check:

    Negative lookbehind + positive lookahead = /(?
Hint: Negative lookbehind excludes prefix, positive lookahead confirms suffix [OK]
Common Mistakes:
  • Forgetting space after 'wild' in lookbehind
  • Using positive lookbehind instead of negative
  • Adding space in lookahead incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard