Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preg match if not [duplicate]

Is it possible to do a preg_match() on something that shouldn't be a match whilst still returning true?

For example, at the moment we have...

if (preg_match('#^Mozilla(.*)#', $agent)) {

We want to check if the Mozilla string is not in $agent, but still have preg_match return true.

We can't change it to:

if (!preg_match('#^Mozilla(.*)#', $agent)) {
like image 974
fire Avatar asked Jun 06 '11 15:06

fire


People also ask

How preg match works?

preg_match in PHP function is used to search the string for a pattern and return a Boolean value. The search generally starts from the initial character of the string.

Is preg match case-insensitive?

preg_match is case sensitive. A match. Add the letter "i" to the end of the pattern string to perform a case-insensitive match.

What does preg_ match return?

The preg_match() function returns whether a match was found in a string.

Why we use preg_ match in PHP?

The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns contained in the search pattern, if applicable.


1 Answers

What you want is a negative lookahead, and the syntax is:

if (preg_match('#^(?!Mozilla).#', $agent)) {

Actually, you can probably get away with just #^(?!Mozilla)# for this. I don't know how PHP will feel about a pattern that's nothing but zero-width tokens, but I've tested it in JavaScript and it works fine.


Edit:

If you want to make sure Mozilla doesn't appear anywhere in the string, you could use this...

if (preg_match('#^((?!Mozilla).)*$#', $agent)) {

...but only if you can't use this!

if (strpos($agent, 'Mozilla') !== false) {
like image 182
Justin Morgan Avatar answered Sep 21 '22 03:09

Justin Morgan