如何修正正则表达式,避免匹配administrator并实现可选/规则
Hey there! Let's tackle that regex issue you're facing. The problem with your current pattern is that it doesn't restrict what comes right after "admin" — so "administrator" gets matched because "admin" is at the start, and the rest is incorrectly captured as the controller.
The Solution
We need to enforce that after "admin", either the string ends, or the next character is a / (if there's any后续 content). Here's an adjusted regex that meets all your requirements:
preg_match("/^admin(?:\/(?P<controller>[a-z-]+)?\/?(?P<action>[a-z-]+)?)?$/i", $input_line, $output_array);
Breakdown of the Pattern
Let's break down what each part does to make it clear:
^admin: Strictly matches the start of the string followed by "admin"(?:\/...)?: An optional non-capturing group that ensures any content after "admin" must start with/\/: The mandatory leading slash if there's后续 content(?P<controller>[a-z-]+)?: Optional named capture group for the controller (allows letters and hyphens, can be empty for cases likeadmin/)\/?: Optional slash separating the controller and action(?P<action>[a-z-]+)?: Optional named capture group for the action (also allows letters and hyphens, can be empty)
$: Matches the end of the string, preventing extra characters after valid paths
What It Matches
- ✅
admin(exact match) - ✅
admin/(admin followed by just a slash) - ✅
admin/users(admin with controller) - ✅
admin/users/index(admin with controller and action)
What It Rejects
- ❌
administrator(admin is followed by letters instead of a slash or end of string) - ❌
home(doesn't start with admin)
If you want a slightly more strict version that avoids trailing slashes except for the admin/ case, you could use this pattern instead:
preg_match("/^admin(?:\/(?P<controller>[a-z-]+)(?:\/(?P<action>[a-z-]+))?)?$|^admin\/$/i", $input_line, $output_array);
This one explicitly allows admin/ while disallowing trailing slashes on paths with controllers/actions (like admin/users/).
内容的提问来源于stack exchange,提问作者Chad

