说有人输入这样的URL:
http://i.imgur.com/a/b/c?query=value&query2=value
Run Code Online (Sandbox Code Playgroud)
我想回来: imgur.com
不 i.imgur.com
这是我现在的代码
$sourceUrl = parse_url($url);
$sourceUrl = $sourceUrl['host'];
Run Code Online (Sandbox Code Playgroud)
但这会回来 i.imgur.com
小智 73
检查下面的代码,它应该做得很好.
<?php
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
}
return false;
}
print get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'
?>
Run Code Online (Sandbox Code Playgroud)
您需要使用Public Suffix List的包.是的,你可以使用字符串函数arround parse_url()或regex,但它们会在复杂的URL中产生错误的结果.
我建议使用TLDExtract进行域解析,这里是示例代码:
$url = 'http://i.imgur.com/a/b/c?query=value&query2=value';
parse_url($url, PHP_URL_HOST); // will return 'i.imgur.com'
$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse($url);
$result->getFullHost(); // will return 'i.imgur.com'
$result->getSubdomain(); // will return 'i'
$result->getRegistrableDomain(); // will return 'imgur.com'
$result->getSuffix(); // will return 'com'
Run Code Online (Sandbox Code Playgroud)