Can Domain Names Be Validated in PHP Without Regular Expressions?

Mary-Kate Olsen
Release: 2024-11-01 19:29:30
Original
549 people have browsed it

Can Domain Names Be Validated in PHP Without Regular Expressions?

Validating Domain Names in PHP

Can Validation Be Done Without Regular Expressions?

Validating domain names without regular expressions is not recommended due to potential security vulnerabilities and inconsistent results. Regular expressions provide a robust and standardized approach to ensure accuracy.

Regex Pattern for Domain Name Validation

To validate domain names using regular expressions, consider the following pattern:

^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i
Copy after login

This expression comprises multiple criteria:

  • Valid Characters: Ensures domain names contain only alphanumeric characters, hyphens, and periods.
  • Overall Length: Domain names must not exceed 253 characters in length.
  • Individual Label Length: Each label (the part separated by periods) must not exceed 63 characters.

Custom Validation Function

An improved PHP function for domain name validation:

<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)
            &amp;&amp; preg_match("/^.{1,253}$/", $domain_name)
            &amp;&amp; preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name));
}</code>
Copy after login

Test Cases

Domain Name Validation Result
a Yes
0 Yes
a.b Yes
localhost Yes
google.com Yes
news.google.co.uk Yes
xn--fsqu00a.xn--0zwm56d Yes
goo gle.com No
google..com No
google.com No
google-.com No
.google.com No
No
alert( No
. No
.. No
No
- No
No

The above is the detailed content of Can Domain Names Be Validated in PHP 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!