开发者

How can I know if it's a absolute domain name with PHP

I am getting a link and in it there is a href... I want to 开发者_JAVA技巧know if it's a

http://[...].com/file.txt absolute domain name

or

/file.txt

a link that does not have the full URL.

How can I do this with PHP?


Use parse_url and see if you get a scheme and host. For example, this:

$url   = 'http://username:password@hostname/path?arg=value#anchor';
$parts = parse_url($url);
echo $url, "\n", $parts['scheme'], "\n", $parts['host'], "\n\n";

$url   = '/path?arg=value#anchor';
$parts = parse_url($url);
echo $url, "\n", $parts['scheme'], "\n", $parts['host'], "\n\n";

Produces:

http://username:password@hostname/path?arg=value#anchor
http
hostname

/path?arg=value#anchor

Live example: http://ideone.com/S9WR2

This also allows you to check the scheme to see if it is something you want (e.g. you'd often want to ignore mailto: URLs).


You can use preg_match with a regexp to test the format of the url string. You'll need to modify $myurl as necessary, probably passing it in as a variable.

<?php
$myurl = "http://asdf.com/file.txt"; // change this to meet your needs

if (preg_match("/^http:/", $myurl)) {
    // code to handle
    echo 'http url';
}
else if (preg_match("/^\\//", $myurl)) {
    // code to handle
    echo 'slash url';
}
else {
     // unexpected format
    echo 'unexpected url';
}

?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜