我搜索了很多,但我发现许多复杂的例子,对我来说太难理解了。无论如何,我正在尝试写下一个应该遵守的正则表达式:
/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
开头,我想。
如何否定整组单词(admin
或 files
或 login
)?
试试这个:
$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