我正在编写一个调用第三方api的脚本,该脚本需要一个有效的服务器主机名。应允许任何这些格式,例如:
等...
所以,我已经整理了以下脚本来清理服务器的主机名(在用户输入无效条目的情况下):
$server_hostname = 'test';
if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 1:
$server_hostname = 'server.'. $server_hostname;
break;
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
var_dump($server_hostname);
function IsValidHostname($hostname)
{
// Src: http://stackoverflow.com/a/4694816
return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $hostname)
&& preg_match("/^.{1,253}$/", $hostname)
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $hostname)
);
}
该脚本似乎有效。如果提供的主机名无效,则会自动生成随机主机名。以下是一些测试用例:
test -> server1451385708.default-domain.com
test.com -> server.test.com
123-test.com -> server.123-test.com
adam.test.com -> adam.test.com
e-v-e.test.com -> e-v-e.test.com
server12.test.co.uk -> server12.test.co.uk
然而,我不确定这是否相当完美。这是一个失败的测试:
test.co.uk -> test.co.uk
当tld
有2
个部分(例如co.uk)时,我希望结果如下:
test.co.uk -> server.test.co.uk
关于如何实现这一目标的任何想法?
答案 0 :(得分:0)
像这样,这只是涵盖了两个"。":
的情况if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 1:
case 2:
$server_hostname = 'server.'. $server_hostname;
break;
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
或者像这样,无论"的数量如何都会添加信息。":
if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
default:
$server_hostname = 'server.'. $server_hostname;
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
答案 1 :(得分:0)
这是我现在已经解决的问题,让我知道是否有更好的方法:
// Sanitize server's hostname
$serverHostname = strtolower(trim($server['hostname']));
if ($this->IsValidHostname($serverHostname)) {
switch (substr_count($serverHostname, '.')) {
case 1:
case 2:
if (substr($serverHostname, 0, 7) !== 'server.')
$serverHostname = uniqid() .'.'. $serverHostname;
break;
case 0:
$serverHostname = uniqid() .'.default-domain.com';
break;
}
} else {
$serverHostname = uniqid() .'.default-domain.com';
}