I made a function to validate the domain name without any regex.
<?php
function validDomain($domain) {
$domain = rtrim($domain, '.');
if (!mb_stripos($domain, '.')) {
return false;
}
$domain = explode('.', $domain);
$allowedChars = array('-');
$extenion = array_pop($domain);
foreach ($domain as $value) {
$fc = mb_substr($value, 0, 1);
$lc = mb_substr($value, -1);
if (
hash_equals($value, '')
|| in_array($fc, $allowedChars)
|| in_array($lc, $allowedChars)
) {
return false;
}
if (!ctype_alnum(str_replace($allowedChars, '', $value))) {
return false;
}
}
if (
!ctype_alnum(str_replace($allowedChars, '', $extenion))
|| hash_equals($extenion, '')
) {
return false;
}
return true;
}
$testCases = array(
'a',
'0',
'a.b',
'google.com',
'news.google.co.uk',
'xn--fsqu00a.xn--0zwm56d',
'google.com ',
'google.com.',
'goo gle.com',
'a.',
'hey.hey',
'google-.com',
'-nj--9*.vom',
' ',
'..',
'google..com',
'www.google.com',
'www.google.com/some/path/to/dir/'
);
foreach ($testCases as $testCase) {
var_dump($testCase);
var_dump(validDomain($TestCase));
echo '<br /><br />';
}
?>
This code outputs:
string(1) "a" bool(false)
string(1) "0" bool(false)
string(3) "a.b" bool(true)
string(10) "google.com" bool(true)
string(17) "news.google.co.uk" bool(true)
string(23) "xn--fsqu00a.xn--0zwm56d" bool(true)
string(11) "google.com " bool(false)
string(11) "google.com." bool(true)
string(11) "goo gle.com" bool(false)
string(2) "a." bool(false)
string(7) "hey.hey" bool(true)
string(11) "google-.com" bool(false)
string(11) "-nj--9*.vom" bool(false)
string(1) " " bool(false)
string(2) ".." bool(false)
string(11) "google..com" bool(false)
string(14) "www.google.com" bool(true)
string(32) "www.google.com/some/path/to/dir/" bool(false)
I hope I have covered everything if I missed something please tell me and I can improve this function. :)