0

For domain registration I would like to add some verification, just in case if someone would like to go crazy and enter some weird domain names.

This is what I have now:

preg_match('/[^a-zA-Z0-9]/', $domain)

I would like to also add "-" but it cannot be the first or last character. The $domain has to be 2 or more characters at least. and cannot start or end with "-".

RegEx Gurus: any idea how to make this simple? Thank you!

Jonny 5
  • 11,051
  • 2
  • 20
  • 42
Tibby
  • 195
  • 1
  • 15
  • Remember that some urls have underscore and other characters you have not included in your regex above – The One and Only ChemistryBlob May 18 '14 at 15:18
  • try to search for it before asking http://stackoverflow.com/questions/18332148/validate-domain-name-php – ashishmaurya May 18 '14 at 15:21
  • To be completely honest your regex matching should be a little more complex than what you have above...to keep it simple but be more thorough, try to match for the strings http or https, then valid characters for domain name (between www and .com or .whatever), then (\.com$|\.edu$) (etc.) at the least – The One and Only ChemistryBlob May 18 '14 at 15:27
  • I only need the regex for the domain name part. I have the WWW part worked out, and the .com/.net/.org/and so on... Only need a regex for the name itself. like http(s)://www. ONLY-NEED-REGEX-FOR-THIS-PART .com – Tibby May 18 '14 at 15:48

2 Answers2

1

Without considering non-english letters you can use this regex for simple validation to satisfy your rules:

preg_match('/^\w[\w-]*\w$/', $domain)

This will:

  1. Require 2 or more characters
  2. Will hyphens but not as first or last letter as \w is same as [a-zA-Z0-9_]
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • Something is wrong. This works if $domain contains two chars and starts or ends with "-" for example: if $domain is "-a" it works. But it its more than two characters and starts with "-" it wont work. It allows "-abc" to be registered. – Tibby May 18 '14 at 16:06
  • Sorry I forgot anchors, check answer now and also check this demo: http://regex101.com/r/xQ1mO5 – anubhava May 18 '14 at 16:07
1

From ^ start to $ end: At least + one of [a-z0-9] followed by * any amount of (-[a-z0-9]+)

To make it also match [A-Z] add the i (PCRE_CASELESS) modifier. To set a min-length, could use a lookahead at ^ start: (?=.{2}) Checks, if there are at least any 2 characters ahead.

$pattern = '/^(?=.{2})[a-z0-9]+(?:-[a-z0-9]+)*$/i';

(?: Using a non-capturing group for repetition.

test at regex101, regex faq

Community
  • 1
  • 1
Jonny 5
  • 11,051
  • 2
  • 20
  • 42