0
0
PHPprogramming~5 mins

Lookahead and lookbehind in PHP

Choose your learning style9 modes available
Introduction

Lookahead and lookbehind help you find text patterns that come before or after certain parts without including those parts in the result.

You want to find words that come before a specific symbol but don't want to include the symbol.
You need to check if a number is followed by a unit like 'kg' without selecting the unit.
You want to find a word only if it is not preceded by another word.
You want to validate a password that must have a digit somewhere but don't want to capture the digit itself.
Syntax
PHP
/pattern(?=lookahead)/  or  /(?<=lookbehind)pattern/

Lookahead uses (?=...) to check what comes after the pattern.

Lookbehind uses (?<=...) to check what comes before the pattern.

Examples
Find 'foo' only if it is followed by 'bar'. 'bar' is not included in the match.
PHP
/foo(?=bar)/
Find 'bar' only if it is preceded by 'foo'. 'foo' is not included in the match.
PHP
/(?<=foo)bar/
Find 'foo' only if it is NOT followed by 'bar'. This is negative lookahead.
PHP
/foo(?!bar)/
Find 'bar' only if it is NOT preceded by 'foo'. This is negative lookbehind.
PHP
/(?<!foo)bar/
Sample Program

This program finds 'apple' only when it is followed by ' pie' and finds 'tart' only when it is preceded by 'apple '. It prints the matches found.

PHP
<?php
$text = "apple pie and apple tart";

// Find 'apple' only if followed by ' pie'
preg_match_all('/apple(?= pie)/', $text, $matches);
print_r($matches[0]);

// Find 'tart' only if preceded by 'apple '
preg_match_all('/(?<=apple )tart/', $text, $matches2);
print_r($matches2[0]);
OutputSuccess
Important Notes

Lookbehind patterns in PHP must have fixed length (no variable length).

Lookahead and lookbehind do not consume characters; they only check conditions.

Summary

Lookahead checks what comes after a pattern without including it.

Lookbehind checks what comes before a pattern without including it.

They help find patterns with context in text matching.