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 an exact string?
- How to match a single quote in PHP regex?
- How to get the first match when using regex in PHP?
- How to match a double quote in PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to match a word?
- How to use PHP regex to match UTF8?
- How to use PHP regex to match a hexadecimal?
See more codes...