Is it possible without using regular expression?
For example, I want to check that a string is a valid domain:
domain-name abcd example
Are valid domains. These are invalid of course:
domaia@name ab$%cd
And so on. So basically it should start with an alphanumeric character, then there may be more alnum characters plus also a hyphen. And it must end with an alnum character, too.
If it's not possible, could you suggest me a regexp pattern to do this?
EDIT:
Why doesn't this work? Am I using preg_match incorrectly?
$domain = '@djkal'; $regexp = '/^[a-zA-Z0-9][a-zA-Z0-9\-\_]+[a-zA-Z0-9]$/'; if (false === preg_match($regexp, $domain)) { throw new Exception('Domain invalid'); }
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}(\.
The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-). The domain name should be between 1 and 63 characters long. The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-).
<?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 } ?>
Test cases:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With