Preg match if not

Is it possible to do preg_match something that should not match while still returning true?

For example, at the moment we have ...

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

We want to check if Mozilla line is in $ agent, but preg_match still returns true.

Therefore, we cannot change it to ...

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

thanks

+7
source share
3 answers

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

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

In fact, you might just be able to #^(?!Mozilla)# for this. I don’t know how PHP will think of a template that has nothing but zero width markers, but I tested it in JavaScript and it works fine .


Edit:

If you want to make sure that Mozilla does not appear anywhere on the line, you can use this ...

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

... but only if you cannot use it!

 if (strpos($agent, 'Mozilla') !== false) { 
+12
source
 if (preg_match('#^Mozilla(.*)#', $agent) === 0) { 

Hope I didn’t get your question wrong. preg_match will either return 0 (not found), 1 (1 match found, not looking for more), or false (some kind of problem has occurred). I used === to not return true when false returned from preg_match .

+2
source

You can use a negative view:

 #^(?!Mozilla)(.*)# 
+2
source

All Articles