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 to match URL path?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match whitespace?
- How to match a single quote in PHP regex?
- How to use PHP regex to match a year?
- How to match a double quote in PHP regex?
- How to use PHP regex to get a YouTube video ID?
See more codes...