Sandro Antonucci
Sandro Antonucci

Reputation: 1753

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:

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/?

Upvotes: 0

Views: 1414

Answers (1)

Justin Morgan
Justin Morgan

Reputation: 30690

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 / before index.php, if index.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.

Upvotes: 1

Related Questions