SyntaxStudy
Sign Up
PHP Lookahead and Lookbehind in PHP
PHP Advanced 5 min read

Lookahead and Lookbehind in PHP

PCRE Lookahead/Lookbehind

Lookahead (?=...) and lookbehind (?<=...) assert context without consuming characters, enabling complex pattern matching.

Example
<?php
// Positive lookahead: price before " USD"
preg_match_all("/\d+(?= USD)/", "100 USD and 250 USD", $m);
// $m[0] = ["100", "250"]

// Negative lookahead: digits NOT followed by " USD"
preg_match_all("/\d+(?! USD)/", "100 USD 200 EUR", $m);

// Positive lookbehind: digits after "$"
preg_match_all("/(?<=\$)\d+/", "$100 and $250", $m);
// $m[0] = ["100", "250"]

// Negative lookbehind
preg_match_all("/(?<!\$)\d+/", "$100 200 items", $m);
Pro Tip

PHP PCRE lookbehinds must be fixed-width — variable-length lookbehinds cause an error.