user562854
user562854

Reputation:

Check for valid host:port combination

Is there a way to check a valid host:port combination using regex and php?

The regular expression has to make sure that:

Examples of valid combinations:

  1. 95.241.1.5:5423

  2. 2.8.5.2:65532

Examples of INvalid combinations:

  1. 1.2345.12.1:5441

  2. 15.852.32.455:151896841

  3. 65.112.15.32:48trololo

Upvotes: 3

Views: 2225

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336468

^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]):(?:6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{1,3}|[0-9])$

should work, but it's not pretty trying to match numbers with regexes...

In verbose format, a bit more readable:

^
(?:
 (?:
  25[0-5]|        # 250-255
  2[0-4][0-9]|    # 200-249
  1[0-9][0-9]|    # 100-199
  [1-9]?[0-9]     # 0-99
 )  
 \.               # .
){3}              # three times, last segment follows (no dot)
(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])
:                 # :
(?:
 6553[0-5]|       # 65530-65535
 655[0-2][0-9]|   # 65500-65529
 65[0-4][0-9]{2}| # 65000-65499
 6[0-4][0-9]{3}|  # 60000-64999
 [1-5][0-9]{4}|   # 10000-59999
 [1-9][0-9]{1,3}| # 10-9999
 [0-9]            # 0-9
)
$

Upvotes: 5

Related Questions