Jessica Lingmn
Jessica Lingmn

Reputation: 1212

Get the subdomain from a string using php

To get the domain name i am using this code:

<?php
  $myURL   = 'http://answers.yahoo.com/question/index?qid=20130406061745AAmovgl';
  $pattern = '/\w+\..{2,3}(?:\..{2,3})?(?:$|(?=\/))/i';
  if (preg_match($pattern, $myURL, $domain) === 1) {
    $domain = $domain[0];
  }
  $ndomain = "http://$domain";
  echo $ndomain;
?>

but it will output: http://yahoo.com
But, how i can output http://answers.yahoo.com this sub-domain exactly.

Upvotes: 2

Views: 826

Answers (2)

ulentini
ulentini

Reputation: 2412

You can use parse_url()like this:

$urlData = parse_url($myURL);
$host = $urlData['host']; //domain + subdomain

Upvotes: 3

Sampson
Sampson

Reputation: 268326

You should instead use the parse_url function, since it exists to do this very thing.

echo parse_url( $url, PHP_URL_HOST );

Upvotes: 8

Related Questions