how can I get the subdomain in php

1

How can I get the name of the subdomain in php I have my php script works but when you put www.sub.domain.com you take me first www

<?php
$url = 'http://en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;
?>

I want to omit the www

EXAMPLE: link = www

result I want is: sub

    
asked by juan cruz 23.12.2018 в 22:27
source

1 answer

0

This would omit the www if they are present in the string:

function getSubdominio($host_array) {
    $output = array_shift($host_array);
    if ($output === 'www') {
        $output = array_shift($host_array);
    }
    return $output;
}

With that declared function, you can replace this:

$subdomain = $host[0];

... for this:

$subdomain = getSubdominio($host);

** Edition:

The previous solution assumes that there is only one level of subdomains.

If there were more than one, the function would be more versatile like this:

function getSubdominio($host_array, $sub_level=1) {
    $idx = 1 + $sub_level;
    $inv_arr = array_reverse($host_array);
    $output = $inv_arr[$idx];
    if ($output === 'www') {
        $idx += 1;
    }
    // Si se sale del límite, cogemos el último existente
    while($idx >= sizeof($inv_arr) - 1)
    {
        $idx -= 1;
    }
    return $inv_arr[$idx];
}

With that, several levels of subdomains could be handled. For example, if you have:

logos.en.examples.com

To get en :

$subdomain = getSubdominio($host, 1);

//El segundo parámetro es opcional y 1 por defecto
//Se puede omitir en este caso
$subdomain = getSubdominio($host);

And to get logos :

$subdomain =getSubdominio($host, 2);
    
answered by 24.12.2018 / 06:18
source