• February
  • 8th
  • 2009

PHP – how to remove subdomain from url

Posted by MaEl in: Bits-and-Bytes Comments (3)


$doms = array('http://yahoo.co.uk','http://www.yahoo.co.uk','http://www.yahoo.com','http://yahoo.com','http://www.mail.yahoo.com','http://www.mail.yahoo.co.uk');

foreach ($doms as $dom) {
$matches = explode('//',$dom);
$matches = explode('.',$matches[1]);

//http://yahoo.com
if (count($matches) == 2) {
echo $matches[0] . '.' . $matches[1];
} elseif (count($matches) == 3) {

//http://yahoo.co.uk
if (strlen($matches[2]) == 2) {
echo $matches[0] . '.' . $matches[1] . '.' . $matches[2];

//http://www.yahoo.com
} else {
echo $matches[1] . '.' . $matches[2];
}
} elseif (count($matches) == 4) {

//http://www.yahoo.co.uk
if (strlen($matches[3]) == 2) {
echo $matches[1] . '.' . $matches[2] . '.' . $matches[3];

//http://www.mail.yahoo.com
} else {
echo $matches[2] . '.' . $matches[3];
}
} elseif (count($matches) == 5) {

//http://www.mail.yahoo.co.uk
if (strlen($matches[3]) == 2) {
echo $matches[2] . '.' . $matches[3] . '.' . $matches[4];
}
}
}

this should output

http://yahoo.co.uk => yahoo.co.uk
http://www.yahoo.co.uk => yahoo.co.uk
http://www.yahoo.com => yahoo.com
http://yahoo.com => yahoo.com
http://www.mail.yahoo.com => yahoo.com
http://www.mail.yahoo.co.uk => yahoo.co.uk

rather lame method to do it.. should have learn regex…

« decryt ssl key | VPS – how to manual install lxadmin »


3 Responses to “PHP – how to remove subdomain from url”

  1. Monkian Says:

    The problem is:

    http://oh.my.god.you.failed.to.account.for.this.yahoo.com

    is a valid (sub)domain

  2. rizvi Says:

    how to achive:

    mail.yahoo.co.uk => yahoo.co.uk
    mail.yahoo.co.uk/ => yahoo.co.uk

  3. Ryan Says:

    This worked really well, I just replaced
    ('http://yahoo.co.uk','http://www.yahoo.co.uk','http://www.yahoo.com','http://yahoo.com','http://www.mail.yahoo.com','http://www.mail.yahoo.co.uk');

    with

    ('http://'.$_SERVER'SERVER_NAME');

    This allows me to dynamically use the script for multiple sites.

    Thanks!
    Ryan

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>