# Regular expression for range of IP addresses?

Good day, please tell me, the challenge is to determine the following ranges:

77.88.0.0 - 77.88.0.18
77.88.22.0 – 77.88.23.255

He wrote a regular expression:
\$named range1 = "77.88.0.[0-1][0-9]";
\$range2 = "77.88.2[2-3].[0-2][0-9][0-9]";

if (preg_match("77.88.0.3",\$named range1)) {
echo "Entry found.";
} else {
}

Questions:

Tell me what I'm doing wrong?
Properly written regular expression? ( if not, how correctly to those ranges to write regular expressions ) ?
March 19th 20 at 09:29
March 19th 20 at 09:31
To check such things with regexps - is fundamentally wrong. IP address is just a 32-bit integer. Every operating system and almost every language has functions for working with IP addresses and ranges. PHP is no exception:

\$firstIpAsString = '77.88.0.0';
\$lastIpAsString = '77.88.0.18';
\$ipAsString = '77.88.0.111';

\$firstIp = ip2long(\$firstIpAsString);
\$lastIp = ip2long(\$lastIpAsString);
\$ip = ip2long(\$ipAsString);

var_export([
'first' => \$firstIp,
'last' => \$lastIp,
'ip' => \$ip,
'in range?' => \$firstIp <= \$ip && \$ip <= \$lastIp,
], false);
March 19th 20 at 09:33
\$named range1 = "77\.88\.0\.[0-1]?\d";
In General, the range and range bring the ip to an integer and check whether it borders.
March 19th 20 at 09:35
As you wrote, to define the range of IP addresses, converting them to integers. But if the regexps, in your case, you can:
\$named range1 = "77\.88\.0\.([0-9]\$|[1][0-8]\$)";
\$range2 = "77\.88\.(22/23)\.[0-9]+\$";
or in one line:
\$range = '(77\.88\.0\.([0-9]\$|[1][0-8]\$)|77\.88\.(22/23)\.[0-9]+\$)';

Find more questions by tags Regular expressionsPHP