preg_match trailing slash in url
I want to make sure that a visitor is exactly at the homepage of the site. Is this correct to match if the url is:
- www.site.com
- www.site.com/
www.site.com/index.php
preg_match("/^(www.)?(".$host.")(\/)?(index.php)?$/", $url, $matches)
It doesn't seem too formally开发者_开发问答 correct to separate the last two matches like this, but it works Plus is there any browser that doesn't "redirect" a www.site.com to www.site.com/?
Close. I would go with this instead:
preg_match("/^(?:www\.)?(?:".$host.")(?:\/(?:index\.php)?)?(?:\?.*)?$/", $url, $matches)
The differences here are:
- Escaping
.
characters meant as literal dots (a dot normally means "any character except\n
or\r
" in regular expressions). - Requiring a
/
beforeindex.php
, ifindex.php
is present. - Optionally allowing GET parameters (the
\?.*
part). - Non-capturing groups, since you don't seem interested in going through the captures.
Other than that, it looks good to me.
精彩评论