Page 1 of 1

Negative Matching?

Posted: Tue Apr 13, 2010 9:00 pm
by Benjamin
Not sure what this is called. I am looking to match all files in a directory which are not one of:

.
..
.svn

I ended up approaching this by using regex that will exclude these, however I'm wondering how to write regex which will NOT match them.

Here's what I tried, it doesn't work.

Code: Select all

#^(?:[^\.]|[^\.]{2}|[^(?:svn)]).*$#

Re: Negative Matching?

Posted: Wed Apr 14, 2010 12:43 am
by ridgerunner
Try this:

Code: Select all

if (preg_match('/^(?!\.{1,2}$|\.svn$).+$/m', $contents)) {
    # Successful match
} else {
    # Match attempt failed
}

Re: Negative Matching?

Posted: Wed Apr 14, 2010 2:18 am
by Benjamin
Worked perfectly!
No Match .
No Match ..
No Match .svn
Match .htaccess
Match includes
Match images

Re: Negative Matching?

Posted: Sun May 02, 2010 5:38 am
by hypedupdawg
I realise that you have found an expression that works for you - however, it may be easier to use a switch statement if you ever needed to edit it:

Code: Select all

switch ($contents)
{
case ".":
case "..":
case ".svn":
//do nothing
break;
default:
//your code here
}
By leaving out the breaks between the different cases, all the top three cases will result in the same action. The default code will then run for anything that is not those three cases.

Just another option...