从url中解析主机名/域名 , IP地址和端口 返回包含域名和端口的数组
if (!function_exists('get_domain_port_by_url')) {
/**
* get domain/ip and port from url string
* @param mixed $url
* @return array array of domain and port or empty array
*/
function get_domain_port_by_url($url): array
{
// parse the domain or ip address and port number
preg_match('/(([^\/:]+)\.([a-zA-Z0-9]{1,10})(:(\d{2,6}))?)/u', $url, $matches);
if ($matches) {
$mlen = count($matches);
if ($mlen == 4) {
$domain = $matches[1];
$port = 80;
} elseif ($mlen == 6) {
// port is include in the $domain
$domain = sprintf('%s.%s', $matches[2], $matches[3]);
$port = $matches[5];
}
return ['domain' => $domain, 'port' => $port];
} else {
return [];
}
}
}
使用方法/示例:
$arr = get_domain_port_by_url('https://dev.tekin.cn/contactus.html');
$domain=$arr['domain']??''; // 输出: dev.tekin.cn
$domain=$arr['port']??0; // 输出: 80