Consolas
Consolas

Reputation: 35

reg expression: get subdomain if existent

The problem is the following - I want to get the subdomain out of a random url.

  1. the subdomain might exist or not (www.domain.com or domain.com)
  2. I want to get the full subdomain info

For instance, www.somesite.com would get me, using preg_match, an array with

[0] = www.somesite.com
[1] = www

Similarly, the domain somesite.com would get me:

[0] = somesite.com

(and no [1] would be indexed)

I was using the following reg_exp:

preg_match('/[www.]?([0-9A-Za-z-]+)'/', $_SERVER['SERVER_NAME'], $array);

but for www.somesite.com it is getting me an array with

[0] = www.somesite.com
[1] = ww (the last w seems to be missing)

Any tips on how to accomplish this?

Upvotes: 0

Views: 88

Answers (2)

svante
svante

Reputation: 1385

A tip to get you on your way:

^(.+\.|)([^\.]+\.[^\.]+)$

should give you

[0] = www.somesite.com
[1] = www.
[2] = somesite.com

and

[0] = www.another.somesite.com
[1] = www.another.
[2] = somesite.com

and

[0] = somesite.com
[1] = 
[2] = somesite.com

Upvotes: 1

anubhava
anubhava

Reputation: 784868

I haven't looked at your full regex but this part of the regex is sure a problem:

[www.]?

List of characters inside square brackets means only one is matched. This means either w or dot and that too optional because of ?

It should have been:

(www\.)?

Upvotes: 3

Related Questions