Home » Php » php – Preg match if not

php – Preg match if not

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

So we can’t change it to…

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

Thanks

How to&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) {

Answer:

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

I hope I have not misunderstood your question. preg_match will either return 0 (not found), 1 (found 1 match, does not search for more), or false (some problem occurred). I used === not to return true when false is returned from preg_match.

Answer:

You can use negative lookahead like this:

#^(?!Mozilla)(.*)#