NoNameZ
NoNameZ

Reputation: 795

Remove subdomain from url

So i have this kind of code, which returns the domain name, but i cant figure out how to remove subdomain, can anyone help ?

$link='http://www.lol.wwwyoursitewww.com/aaaaa/ggghd/site.php?sadf=asg';
preg_match('/^http\:\/\/www.(.*?)\/.*/i', $link, $link_domain);
echo $link_domain[1]; 

Upvotes: 2

Views: 3033

Answers (3)

jcarlosweb
jcarlosweb

Reputation: 974

Get host without subdomain. Work with www

/**
   * Get Host without subdomain
   * @param $host
   * @return string
   */
  public static function giveHost($host): string
  {
    $newHost    = $host;
    $host_array = explode('.', $host);
    $countDot   = count($host_array);
    if ($countDot > 2){
      $newHost = $host_array[$countDot-2].'.'.$host_array[$countDot-1];
      if (preg_match('/www/', $host)){
        $newHost = 'www.'.$newHost;
      }
    }
    return $newHost;
  }

Upvotes: 0

Alexey
Alexey

Reputation: 7247

$link='http://www.lol.wwwyoursitewww.com/aaaaa/ggghd/site.php?sadf=asg';
preg_match('!www((\.(\w)+))+!', $link, $match);
$link_arr=(explode(".", $match[0]));
echo $link_domain = $link_arr[count($link_arr)-1];

Output: com

Upvotes: 0

Adam
Adam

Reputation: 36703

I'd use the built-in parse_url to do as much as possible, which will just leave you with the domain name to sort out. I was a little unclear on the requirements. What is the expected output? - just wwwyoursitewww.com? or http://wwwyoursitewww.com/aaaaa/ggghd/site.php?sadf=asg

$link='http://www.lol.wwwyoursitewww.com/aaaaa/ggghd/site.php?sadf=asg';

$url = parse_url($link);

if (preg_match("/(www.*?)\.(.*)/", $url['host'], $m)) {
  $url['host'] = $m[2];
}

$rebuild = $url['scheme'] . '://' . $url['host'] . $url['path'] . '?' . $url['query'];

echo "$rebuild\n";

Upvotes: 1

Related Questions