PHP RegExp returns a statement to get the opposite match

This is my first question, so please be beautiful :). I'm trying to create a regular expression to get an array of IP addresses that are valid (OK, at least with the appropriate IPv4 format) and is NOT a private IP address according to RFC 1918. So far I have figured out a way to get the exact opposite. I mean succcssfuly mapping private IPs, so all I need is a way to return a statement. This is the code so far:

// This is an example string $ips = '10.0.1.23, 192.168.1.2, 172.24.2.189, 200.52.85.20, 200.44.85.20'; preg_match_all('/(?:10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}/', $ips, $matches); print_r($matches); // Prints: Array ( [0] => Array ( [0] => 10.0.1.23 [1] => 192.168.1.2 [2] => 172.24.2.189 ) ) 

And as a result, I want:

 Array ( [0] => Array ( [0] => 200.52.85.20 [1] => 200.44.85.20 ) ) 

I tried changing the first part of the expression (lookahead) to negative (?!), But this messed up the results and didn't even switch the result.

If you need more information, please feel free to ask, thanks a lot in advance.

+4
source share
2 answers

If all you want to do is to exclude the relatively small ip range, you can do it (if I haven't made any typos):

 /(?!\b(?:10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b)\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/ 

Example in Perl:

 use strict; use warnings; my @found = '10.0.1.23, 192.168.1.2, 172.24.2.189, 200.52.85.20, 200.44.85.20' =~ / (?! \b (?: 10\.\d{1,3} | 172\. (?: 1[6-9] | 2\d | 3[01] ) | 192\.168 ) \.\d{1,3} \.\d{1,3} \b ) \b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b) /xg; for (@found) { print "$_\n"; } 

Output:

200.52.85.20
200.44.85.20

0
source

There is a PHP function for this: filter_var () . Check these constants: FILTER_FLAG_IPV4 , FILTER_FLAG_NO_PRIV_RANGE .

However, if you still want to solve this with regular expressions, I suggest you divide the problem into two parts: first you extract all the IP addresses, then filter out the private ones.

+4
source

All Articles