PHP Function to Check if a String is a Valid Domain Name via Regex


Given a string e.g. “domain.com” we want to find out if it is a valid domain string name. We can do this in PHP via Regx aka Regular Expression. We can perform 3 checks: first, the characters need to be lowercase/uppercases, digits, hypens, and dots. Second, the overall domain length should between 1 to 253. Lastly, the length of each label (separated by dots) should be no longer than 63 characters.

The following is a handy PHP function can validate the domain string:

1
2
3
4
5
6
7
8
<?php
if (!function_exists("is_valid_domain_name")) {
  function is_valid_domain_name($domain_name) {
      return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
              && preg_match("/^.{1,253}$/", $domain_name) //overall length check
              && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)   ); //length of each label
  }
}
<?php
if (!function_exists("is_valid_domain_name")) {
  function is_valid_domain_name($domain_name) {
      return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $domain_name) //valid chars check
              && preg_match("/^.{1,253}$/", $domain_name) //overall length check
              && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)   ); //length of each label
  }
}

For example:

1
2
is_valid_domain_name("domain.com"); // true
is_valid_domain_name("--anothers"); // false
is_valid_domain_name("domain.com"); // true
is_valid_domain_name("--anothers"); // false

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
214 words
Last Post: A Simple BASH Script to Search and Kill Processes By Name
Next Post: Teaching Kids Programming - Using Heap (Priority Queue) to Generate Nth Ugly Number

The Permanent URL is: PHP Function to Check if a String is a Valid Domain Name via Regex

One Response

  1. FunkyFlo

Leave a Reply