Home  >  Article  >  Backend Development  >  Why Can\'t I Validate Domains in PHP Without Regular Expressions?

Why Can\'t I Validate Domains in PHP Without Regular Expressions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 05:01:02251browse

Why Can't I Validate Domains in PHP Without Regular Expressions?

PHP domain name verification

Question: How to verify domain name in PHP without using regular expressions?

Verification requirements:

  • Starts with a letter or number
  • Can contain letters, numbers and hyphens
  • Starts with Ending with a letter or number
  • Length between 1 and 253 characters
  • Each label length between 1 and 63 characters

Possible answers:

Domain name validation without using regular expressions is not possible as multiple rules and restrictions need to be checked.

Regular expression pattern:

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

Meaning:

  • ^ and $ anchor strings the beginning and end of.
  • [a-zd] matches letters or numbers.
  • (-*[a-zd])* matches zero or more letters or numbers separated by hyphens.
  • . Matches a period.
  • {} specifies the number of repetitions.

Sample code:

<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
            &amp;&amp; preg_match("/^.{1,253}$/", $domain_name) //overall length check
            &amp;&amp; preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $domain_name)   ); //length of each label
}</code>

Test case:

域名 有效性
a Y
0 Y
a.b Y
localhost Y
google.com Y
news.google.co.uk Y
xn--fsqu00a.xn--0zwm56d Y
goo gle.com N
google..com N
google.com N
google-.com N
.google.com N
N
alert( N
. N
.. N
N
- N
[] N

The above is the detailed content of Why Can\'t I Validate Domains in PHP 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