开发者

URL parse function

开发者 https://www.devze.com 2022-12-21 00:44 出处:网络
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

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


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";


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 =)


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消