Home  >  Article  >  Backend Development  >  How to Validate Domain Names in PHP: With or Without Regular Expressions?

How to Validate Domain Names in PHP: With or Without Regular Expressions?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 06:37:01900browse

How to Validate Domain Names in PHP: With or Without Regular Expressions?

How to Validate Domain Names in PHP

When working with domains, ensuring their validity becomes crucial for preventing malicious activities or erroneous inputs. In this article, we will explore how to validate domain names in PHP, both with and without using regular expressions.

Validation Without Regular Expressions

Although not recommended due to potential limitations, it is possible to perform basic domain name validation without regular expressions. This involves checking the following criteria:

  • The domain name must start with an alphanumeric character.
  • It can contain additional alphanumeric characters or hyphens.
  • It must end with an alphanumeric character.

For example, the following strings would be considered valid domains:

domain-name
abcd
example

While the following would be invalid:

domaia@name
ab$%cd

Validation Using Regular Expressions

Regular expressions provide a more robust and reliable method for validating domain names. The following regular expression pattern can be used for this purpose:

/^[a-zA-Z0-9][a-zA-Z0-9\-\_]+[a-zA-Z0-9]$/

Example Code

The following PHP function validates domain names using the provided regular expression pattern:

<code class="php">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
    );
}</code>

The above is the detailed content of How to Validate Domain Names in PHP: With or Without Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn