php-regexHow to use negative lookahead in PHP regex?
Negative lookahead is a powerful tool in PHP regex that allows you to match a pattern only if it is not followed by another pattern. It is written as (?!pattern)
and is placed after the pattern you want to match.
For example, the following code will match any string that does not end with ing
:
$string = 'This is a test string';
$pattern = '/\w+(?!ing)$/';
if (preg_match($pattern, $string)) {
echo 'Match found!';
}
Output example
Match found!
The code consists of the following parts:
$string
: The string to be matched.$pattern
: The regular expression pattern. It consists of\w+
which matches one or more word characters, followed by(?!ing)
which is the negative lookahead assertion that matches only if the pattern is not followed bying
, and$
which matches the end of the string.preg_match()
: The PHP function used to match the pattern against the string.echo
: The statement used to output the result.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match special characters?
- How to use PHP regex to match a year?
- 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 an XML tag?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
- How to use PHP regex to match a zip code?
See more codes...