Reputation: 2649
I have to match the word 'like'
without the word 'not'
before it. In the example below, there is a 'not'
before the word 'like'
so it shouldn't have matched it. How would I fix this?
$tempInput = "i do not like to fail";
if (preg_match("~(?!not )(like)~", $tempInput, $match)) {
print_r($match);
}
Result:
Array ( [0] => like [1] => like )
Need Result:
Null
Upvotes: 0
Views: 403
Reputation:
Here's a little regex magic.
It's easy to restrict using a fixed width lookbehind assertion.
For example, noob's regex (?<!not )like
matches not like
invalid form's
all day long (not good).
But this (?<!not)(?<!\s)\s*\b(like)
will match as though a variable
length lookbehind is legal in php.
In an ideal world it would be this (?<!not\s+)like
variable.
So, I leave this for anybody who wants wonder how it works.
The like
word is always in capture group 1.
As a bonus the like
group can be any regex sub-expression.
(?<! not ) # Guard, Not 'not' behind
(?<! \s ) # Guard, Not whitespace behind
\s* # Optional whitespace that can't be backtracked
\b # Word boundary
( like ) # (1), 'like'
Upvotes: 1
Reputation:
A negative lookbehind
for literal string not
like this will do.
Regex: /(?<!not )like/
Explanation:
(?<!not )
will look behind
and check if there is word not
.
like
if it is not present then like
will be matched.
Upvotes: 2