5

我搜索了很多,但我发现了很多复杂的例子,对我来说太难理解了。无论如何,我正在尝试写下一个应该尊重的正则表达式:

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

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

我试过一个简单的,只用一个词:#^(\/)([^admin])#即以/不以单词开头的东西开头和后面admin。我想它正在使用/foo/bar但失败了,/a/foo因为它以 开头a

如何否定一整组单词(adminfileslogin)?

4

1 回答 1

5

尝试这个:

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

或者

$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>";
}

输出:

Matched :/foo
Matched :/foo/bar
Not Matched:/login
Not Matched:/admin
Not Matched:/admin/foo
Matched :/files
于 2013-09-01T12:11:31.887 回答