Home > Article > Backend Development > How to Validate Domain Names in PHP Without Regular Expressions?
PHP Domain Name Validation Without Regular Expressions
Many developers face the need to validate domain names, ensuring they conform to specific formatting rules. While regular expressions are commonly used for this task, they can be complex and potentially prone to errors. This article explores a solution for validating domain names in PHP without relying on regular expressions.
In certain situations, such as when working with legacy systems or when dealing with strict character limitations, it may be necessary to validate domain names without resorting to regular expressions. The following function achieves this by implementing a series of logical checks:
<code class="php">function is_valid_domain_name($domain_name) { // Validate alphanumeric characters if (!preg_match("/^[a-zA-Z0-9]+$/", $domain_name)) { return false; } // Validate length of each label $labels = explode(".", $domain_name); foreach ($labels as $label) { if (strlen($label) < 1 || strlen($label) > 63) { return false; } } // Validate overall length if (strlen($domain_name) > 253) { return false; } return true; }</code>
This function ensures that domain names begin and end with alphanumeric characters and that each label within the domain name adheres to the specified length restrictions. It also validates the overall length of the domain name.
Test Cases
The following test cases demonstrate the effectiveness of this validation function:
<code class="php">is_valid_domain_name? [a] Y is_valid_domain_name? [0] Y is_valid_domain_name? [a.b] Y is_valid_domain_name? [localhost] Y is_valid_domain_name? [google.com] Y is_valid_domain_name? [news.google.co.uk] Y is_valid_domain_name? [xn--fsqu00a.xn--0zwm56d] Y is_valid_domain_name? [goo gle.com] N is_valid_domain_name? [google..com] N is_valid_domain_name? [google.com ] N is_valid_domain_name? [google-.com] N is_valid_domain_name? [.google.com] N is_valid_domain_name? [<script] N is_valid_domain_name? [alert(] N is_valid_domain_name? [.] N is_valid_domain_name? [..] N is_valid_domain_name? [ ] N is_valid_domain_name? [-] N is_valid_domain_name? [] N</code>
By following these logical checks, this function provides a reliable way to validate domain names without the need for regular expressions. This approach enhances flexibility and reduces the potential for errors when validating domain names in PHP.
The above is the detailed content of How to Validate Domain Names in PHP Without Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!