Computer >> Computer tutorials >  >> Programming >> PHP

How to validate domain name in PHP?


The domain name can be validated using the below code in PHP −

Example

<?php
function is_valid_domain_name($domain_name) {
   return (preg_match("/^([a-zd](-*[a-zd])*)(.([a-zd](-*[a-zd])*))*$/i", $domain_name) //valid characters check
   && preg_match("/^.{1,253}$/", $domain_name) //overall length check
   && preg_match("/^[^.]{1,63}(.[^.]{1,63})*$/", $domain_name) ); //length of every label
}
?>
$domain_name = 'https://tutorialspoint.com'
is_valid_domain_name($domain_name)

Output

This will produce the following output −

$domain_name = 'https://tutorialspoint.com' is_valid_domain_name($domain_name)

In the above code, the ‘preg_match’ function is used to match the domain_name passed as an argument to the user-defined function ‘is_valid_domain_name’.