if we have
$url = "http://subdomain.domin.ext/somepath/file.php";
how to get the domain.ext
when I used
$parse = parse_url($url);
$domin = $parse[host];
then
echo "$domain"; //this returns subdomain.domin.ext
is there any idea to get domain.ext?
$url = "http://subdomain.domin.ext/somepath/file.php";
$parse = parse_url($url);
$domain = $parse['host'];
$lastDot = strrpos($domain,'.');
$ext = substr($domain,$lastDot+1);
This will get you "ext" (e.g. "com" or "gov"). In the case of something like amazon.co.uk, it will give you "uk". If you need "co.uk", you will need to add logic to detect certain TLDs (e.g. "uk") and go to the second dot on those cases.
<?php
$url = "http://subdomain.domain.ext/somepath/file.php";
$parse = parse_url($url);
$domain = substr(strrchr($parse['host'], '.'), 1);
$domain = substr(strrchr(substr($parse['host'], 0, -strlen($domain)), '.'), 1). '.'. $domain;
if(in_array(strstr($domain, '.', true), array('co', 'com', 'net', 'org', 'edu', 'gov', 'mil')))
{
$domain = substr(strrchr(substr($parse['host'], 0, -strlen($domain)), '.'), 1). '.'. $domain;
}
?>
If you have a specific domain with different TLDs, like mysite
with .co.uk
and .com
, than you can basically do the following:
$url = 'http://mysite.co.uk/some-dir/';
$domain_pos = strpos($url, 'mysite');
$domain = substr($url, $domain_pos);
$ext_pos = strpos($domain, '/');
if($ext_pos !== false) { // extra check for paths/sub-dirs
$domain = substr($domain, 0, $ext_pos);
}
echo $domain;
Returns mysite.co.uk
or whatever TLD that gets assigned to the $url
.
Note the extra check for paths and sub directories. :)
精彩评论