PCRE Lookahead/Lookbehind
Lookahead (?=...) and lookbehind (?<=...) assert context without consuming characters, enabling complex pattern matching.
Lookahead (?=...) and lookbehind (?<=...) assert context without consuming characters, enabling complex pattern matching.
<?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);
PHP PCRE lookbehinds must be fixed-width — variable-length lookbehinds cause an error.