Fetch server name

Asked

Viewed 49 times

1

I would like your help for the following problem, I have this code.

function encontrarValor($url){

    $dominio = explode(".", parse_url($url, PHP_URL_HOST));
    return $dominio[0];

}

It lets you return the host name almost seamlessly. With everything if the host address has www, it puts the server name as www. I would like your help to readjust this code so that even if the url server whether or not www, can perfectly identify the server name.

1 answer

0


In this case, I think it would solve:

function encontrarValor($domain)
{
    if (preg_match('/(http(s)?:\/\/)?(www\.)?(.+)/', $domain, $matches)){
        return explode('/',$matches[4])[0];
    }
}
echo encontrarValor('http://www.teste.com.br/url-123');
echo "<br>";
echo encontrarValor('http://teste.com.br/url-123');

Example in IDEONE

  • If you do the explode at the point, so there’s no way $dominio[0] have a point to match the regular expression.

  • Unfortunately the code is showing error here Return preg_replace('/(http(s)?: //)? www./',''$domain);

  • See if it works now...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.