php-regexHow to use PHP regex lookbehind?
PHP regex lookbehind is a feature of regular expressions that allows you to match a pattern only if it is preceded by another pattern. It is written as (?<=pattern)
and is used to match a pattern only if it is preceded by another pattern.
Example code
$string = 'This is a string';
$pattern = '/(?<=This\s)is/';
if (preg_match($pattern, $string)) {
echo 'Match found';
}
Output example
Match found
Code explanation
$string = 'This is a string';
: This is the string that we are searching in.$pattern = '/(?<=This\s)is/';
: This is the regular expression pattern. The(?<=This\s)
part is the lookbehind assertion, which means that the pattern will only match if it is preceded by the stringThis
.if (preg_match($pattern, $string)) {
: This is the condition that checks if the pattern matches the string.echo 'Match found';
: This is the output that will be printed if the pattern matches the string.
Helpful links
More of Php Regex
- How to match a space using PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a double quote in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to match a single quote in PHP regex?
- How to use PHP regex to match URL path?
See more codes...