Very quick function to test a domain name is valid:
function validDomain($domain) { // Test domain is actually valid if (preg_match('/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/i', $domain)) { return TRUE; } return FALSE; }
The key here is the regular expression (delimited by the forward slashes at each end):
/^[a-z]+([a-z0-9-]*[a-z0-9]+)?(.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$/
This basically translates as follows
- ^[a-z]+ : First chacter must be alphabet
- ([a-z0-9-]*[a-z0-9]+) : A group. The first character may be in the range, a-z or 0-9, or a hyphen. This pattern can repeat, although the last character may not be a hyphen
- ? : That last group is optional
- (. : Start of next group, and it must be a dot
- ([a-z]+ : First letter must be in range a-z
- ([a-z0-9-]*[a-z0-9]+)? : Then an optional group of a-z, 0-9 and hypen, though last character may not be hyphem (as above)
- )+) : Do the last bit at least once
- * : The last bit is optional and can repeat as much as you like
- $: And that’s the end of the string
It’s not a perfect reg-exp for the job, but it does the job where a quick quick is required (user signups fro example), rather than mission critical domain testing.
A good tool for testing your regular expressions can be found here