Reputation:
Is there a way to check a valid host:port
combination using regex and php?
The regular expression has to make sure that:
host
is a valid IP (containing four 1-3 digit numbers separated by 3 dots, number in range of 1-255):
port
is a valid number between 0 and 65535Examples of valid combinations:
95.241.1.5:5423
2.8.5.2:65532
Examples of INvalid combinations:
1.2345.12.1:5441
15.852.32.455:151896841
65.112.15.32:48trololo
Upvotes: 3
Views: 2225
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