Home > Article > Backend Development > How to Validate Domain Names in PHP: With or Without Regular Expressions?
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.
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:
For example, the following strings would be considered valid domains:
domain-name abcd example
While the following would be invalid:
domaia@name ab$%cd
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]$/
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!