Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-31 06:37:01
Original
997 people have browsed it

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
Copy after login

While the following would be invalid:

domaia@name
ab$%cd
Copy after login

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]$/
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template