tags:

views:

94

answers:

4
+2  Q: 

URL parse function

Hello,

Given this variable:

$variable = foo.com/bar/foo

What function would trim $variable to foo.com ?

Edit: I would like the function to be able to trim anything on a URL that could possibly come after the domain name.

Thanks in advance,

John

A: 

I'm using http://www.google.com/asdf in my example

If you're fine with getting the subdomain as well, you could split by "//" and take the 1th element to effectively remove the protocol and get www.google.com/asdf

You can then split by "/" and get the 0th element.

That seems ugly. Just brainstorming here =)

ItzWarty
+3  A: 

Working for OP:

$host = parse_url($url, PHP_URL_HOST);

The version of PHP I have to work with doesn't accept two parameters (Zend Engine 1.3.0). Whatever. Here's the working code for me - you do have to have the full URL including the scheme (http://). If you can safely assume that the scheme is http:// (and not https:// or something else), you could just prepend that to get what you need.

Working for me:

$url = 'http://foo.com/bar/foo';

$parts = parse_url($url);
$host = $parts['host'];

echo "The host is $host\n";
Jesse Millikan
Hmm... it's not working for me.
John
Which version? Both of them?
Jesse Millikan
The second one didn't work... but then I tried the first one and it did, so I gave you credit for the answer. Thanks!
John
A: 

Try this:

function getDomain($url)
{
    if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) === FALSE)
    {
        return false;
    }
    /*** get the url parts ***/
    $parts = parse_url($url);
    /*** return the host domain ***/
    return $parts['scheme'].'://'.$parts['host'];
}

$variable = 'foo.com/bar/foo';
echo getDomain($variable);
Sarfraz
why down vote please.........?
Sarfraz
Dunno if that's why, but this is way over complicated for just getting a host :P
henasraf
@henasraf: thanks but implementation is inside the funtion, however it works :)
Sarfraz
A: 

You can use php's parse_url function and then access the value of the key "host" to get the hostname