How to match a string with an optional "/" at the end?
I am trying to match a URL such as;
http://www.testing.com/documents/dashboard
What I want is to match "/documents开发者_Python百科/dashboard" or "/documents/dashboard/". How can be this done?
preg_match('/^\/documents\/dashboard[\/|]$/i', $_SERVER['REQUEST_URI']);
This doesn't work? What should I enter after pipe (|) character in [] block to cover "nothing" as well?
[\/|]$
is wrong, because []
creates a character class. So what you are matching there is /
or |
followed by end of string. To do what you were thinking of:
preg_match('~^/documents/dashboard(/|$)$~', $_SERVER['REQUEST_URI']);
Although I think it's easier to use:
preg_match('~^/documents/dashboard/?$~', $_SERVER['REQUEST_URI']);
/?
means match the /
character 1 or 0 times.
Tip: If you use a delimiter other than /
, you won't have to escape forward slashes in the pattern.
preg_match('/^\/documents\/dashboard\/?$/i', $_SERVER['REQUEST_URI']);
People often use it at the end of their regex, but it can in fact be used anywhere. Although in your case it's just simpler to use the ?
quantifier.
Or, if you absolutely want to use $
, the following would work too:
/^\/documents\/dashboard(\/|$)$/i
精彩评论