Lookbehind in PHP Regex
In the previous lesson, we covered lookahead.
Similarly, there is positive lookbehind
- (?<= ). In the following
example, the replacement will occur only if
'aaa' is preceded by 'x':
<?php
preg_replace('#(?<=x)aaa#', '!', 'xaaa'); // returns 'x!'
?>
And there is also negative lookbehind
- (?<! ). In the following example, the replacement
will occur only if 'aaa'
is not preceded by 'x':
<?php
preg_replace('#(?<!x)aaa#', '!', 'baaa'); // returns 'b!'
?>
Given a string with variables:
<?php
$str = '$aaa $bbb $ccc';
?>
Get an array of variable names from this string (without the dollar sign).