问题
I am stuck with something I know must be simple but been going round in circles for a while now.
I want to create a regular expression for use with a cms routing feature using php and preg_match that matches any URL that doesn't begin with the string 'admin/' as somedomain.com/admin/ will be the admin part of the cms.
I have tried so far
preg_match('#^([^admin])+(.+)$#', 'mens-books'))
which fails as the url string 'mens-books' I am looking for is a match against the letter m in the string 'admin' so it fails.
I have tried doing it like this also:
preg_match('#^([^admin$])+(.+)$#', 'mens-books'))
as a dollar symbolises the end of string but that didn't work either.
I then did this:
preg_match('#^[?!=admin]+(.+)$#', 'mens-books'))
which returned true but only I think because the ?!= in the regex now will match anything that is beginning with a, d, m, i or n.
Is anyone able to help with this please. I am open to any suggestions.
Thankyou.
Matt
回答1:
if (substr($url, 0, 6) !== 'admin/')
{
echo 'Yippie';
}
But to answer the regex question. When you use square brackets, you're specifying a character class. That means [admin]
matches a single character that is either an a
, a d
an m
an i
or an n
. If you skip the brackets, you're matching a literal string. But, as my code proofs, it is not needed to use regex at all if you need to check if a string starts with a fixed substring.
回答2:
If you want to use regular expressions, what you are looking for is something called negative lookahead, which is a zero-width assertion (it checks for the existence or lack of text without 'eating' it). It would work something like this:
^(?!admin\/)
Here are some specific preg_match examples:
preg_match('/^(?!admin\/)/', 'mens-books'); // true
preg_match('/^(?!admin\/)/', 'admin/mens-books'); // false
preg_match('/^(?!admin\/)/', 'admin-mens-books'); // true
回答3:
the brackets [] are used for any single character [admin] is a, d, m, i, or n not admin, what you probably want is (admin). So anything that begins with admin would be /^(admin).*$/ then the easiest way is to put a not in your code.
example (not a php coder so sorry in advance):
$pattern = '/^(admin)\/.*$/'
if (preg_match($pattern, $url) == 1) {
$match = true;
} else {
$match = false;
}
that is assuming your trying to get back a boolean
回答4:
Im not entirely sure I follow but dont you just want
preg_match('^(/)?admin(/)?.*', 'mens-books'))
eg starts either with /admin or admin
回答5:
Try ^(?!admin/).*$
but I think comparing a substring is much faster.
来源:https://stackoverflow.com/questions/6285677/help-with-regex-to-match-any-url-but-that-of-admin-folder