How to validate domain name in PHP?


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

Example

 Live Demo

<?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’.

Updated on: 07-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements