0

I want to validate a domain .The expression must only be in the format .

   anywordwithoutspace.any

Here's my code

<?php
function validatereg($str1) {
    //validate domain
    if(preg_match('/^([a-z0-9])*(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $str1) {
        //valid domain
    }
    else {
        //not a valid domain
    }
}
?>

I am not sure if its correct. Also please take note that after the period(which was 'any') can be any letter of maximum 4 letters.

Thanks in advance.

Jenz
  • 8,009
  • 6
  • 38
  • 69
CudoX
  • 915
  • 2
  • 18
  • 29
  • possible duplicate of [Domain name validation with RegEx](http://stackoverflow.com/questions/10306690/domain-name-validation-with-regex) – Rikesh Mar 20 '14 at 05:29

3 Answers3

1

You'd better use filter_var with FILTER_VALIDATE_URL:

if (filter_var('http://example.com', FILTER_VALIDATE_URL)) {
    echo "Domain is valid\n";
}
Toto
  • 83,193
  • 59
  • 77
  • 109
-1
 if (preg_match("!"#$%&\'()*+,-./@:;<=>[\\]^_`{|}~", $myString)) 
    {
       //valid url
    }

This should do...

Amit
  • 2,801
  • 3
  • 16
  • 28
-1
<?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
}
?>
Sandy
  • 15
  • 4
  • this one accepts local domains (like "localhost") It will even accept a phone number "123-332-123" and it will reject but valid UTF 8 domains. Also you "borrowed" it from another answer. – John Nov 17 '18 at 01:54