6

I've searched a lot but I've found many complicated examples, too hard to understand for me. Anyways I'm trying to write down a regular expression that should honor:

/foo     // should match
/foo/bar // should match

/login     // shouldn't match
/admin     // shouldn't match
/admin/foo // shouldn't match
/files     // shouldn't match

I've tried with a simple one, just with one word: #^(\/)([^admin])# that is starting with / and followed by something not starting with the word admin. It's working with /foo/bar but fails with /a/foo because it's starting with a, I suppose.

How can negate an entire set of words (admin or files or login)?

1 Answers1

4

Try this:

$pattern = '#^(\/)((?!admin|login).)*$#';

or

$pattern = '#^(/)((?!admin|login).)(/(.)+)*#';
$array = array(
'/foo',     // should match
'/foo/bar', // should match

'/login',     // shouldn't match
'/admin',     // shouldn't match
'/admin/foo', // shouldn't match
'/files'     // shouldn't match
);

foreach($array as $test){
 if(preg_match($pattern, $test)) echo "Matched :".$test."<br>";
 else echo "Not Matched:".$test."<br>";
}

Output:

Matched :/foo
Matched :/foo/bar
Not Matched:/login
Not Matched:/admin
Not Matched:/admin/foo
Matched :/files