Dimitri Vorontzov
Dimitri Vorontzov

Reputation: 8114

PHP RegEx: a Pattern to Validate the Second Level Domain

Note: this is a theoretical question about PHP flavor of regex, not a practical question about validation in PHP. I am merely using Domain Names for lack of a better example.

"Second Level Domain" refers to the combination of letters, numbers, period signs, and/or dashes that are placed between http:// or http://www. and .com (.co, .info, .etc) .

I am only interested in second level domains that use English version of Latin alphabet.

This pattern:

[A-Za-z0-9.-]+

matches valid domain names, such as stackoverflow, StackOverflow, stackoverflow.co (as in stackoverflow.co.uk), stack-overflow, or stackoverflow123.

However, the same pattern would also match something like stack...overflow, stack---over--flow, ........ , -------- , or even . and -.

How can that pattern be rewritten, to indicate that period signs and dashes, even though they can be used multiple times in a node,

Thank you in advance!

Upvotes: 2

Views: 1422

Answers (2)

Aleks G
Aleks G

Reputation: 57336

I think something like this should do the trick:

^([a-zA-Z0-9]+[.-])*[a-zA-Z0-9]+$

What this tries to do is

start at the beginning of string, end at the end

one or more letter or digit
followed by either dot or hypen

the group above repeated 0 or more times

followed by one or more letter or digit

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272376

Assuming that you are looking for a regex that does not allow two consecutive . or - you can use:

^[a-zA-Z0-9]+([-.][a-zA-Z0-9]+)*$

regexr demo

Upvotes: 1

Related Questions