如何使用fnmatch匹配指定URL?现有匹配模式失效求解决方案
Ah, I see the issue here—you're mixing up regular expression syntax with shell-style wildcards, which is why your fnmatch pattern isn't working. Let me break this down for you.
fnmatch uses shell glob patterns, not PCRE regular expressions. The + character in your pattern user/[0-9]+ is treated as a literal plus sign, not a "one or more" quantifier. That's why it can't match URLs like http://deploy.local/user/12.
Let's split this into two separate patterns for each of your target URLs:
1. Match http://deploy.local/user/[digits] (e.g., /user/12)
To match any sequence of one or more digits after /user/, use a glob pattern that targets digits and allows any length of them:
// Full pattern for the numeric ID URL fnmatch("http://deploy.local/user/[0-9]*", $url);
[0-9]matches a single digit*matches zero or more additional characters (so this covers 1-digit, 2-digit, etc., IDs)- If you need to ensure there are no extra characters after the digits (e.g., block
/user/12abc), you could combine this with a check that the part after/user/is purely numeric, but glob patterns alone can't enforce "only digits" for arbitrary lengths—they're less strict than regex here. For most use cases though, the above pattern works perfectly.
2. Match http://deploy.local/user/tree
For the fixed /tree path, you can use an exact glob pattern (or a wildcard if you need to allow query parameters):
// Exact match for the /tree URL fnmatch("http://deploy.local/user/tree", $url); // If you need to allow query parameters (e.g., /user/tree?foo=bar) fnmatch("http://deploy.local/user/tree*", $url);
To avoid confusion in the future, remember these key glob rules:
*: Matches any number of any characters (including none)?: Matches exactly one arbitrary character[chars]: Matches a single character from the set/range (e.g.,[0-9],[a-z])- No regex-specific syntax like
+,*(as a quantifier),(), or^/$anchors works here.
内容的提问来源于stack exchange,提问作者Florian Brandt

