Regex to extract only IPv4 addresses from text

a 夏天 提交于 2019-12-10 20:53:49

问题


I've tried to extract only IP addresses from the the given example input, but it extracts some text with it. Here's my code:

$spfreccord="v=spf1 include:amazonses.com include:nl2go.com include:smtproutes.com include:smtpout.com ip4:46.163.100.196 ip4:46.163.100.194 ip4:85.13.135.76 ~all";

 $regexIpAddress = '/ip[4|6]:([\.\/0-9a-z\:]*)/';        
 preg_match($regexIpAddress, $spfreccord, $ip_match);
 var_dump($ip_match);

I'm looking to match only the IPv4 IP address xxx.xxx.xxx.xxx in each column of the table, but it looks like that the $regexIpAddress is not correct.

Can you please help me find the correct regex to extract only the IPv4 IP addresses? Thanks.


回答1:


Use the following regex:

/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/

So for this:

$spfreccord="v=spf1 include:amazonses.com include:nl2go.com include:smtproutes.com include:smtpout.com ip4:46.163.100.196 ip4:46.163.100.194 ip4:85.13.135.76 cidr class v=spf1 ip4:205.201.128.0/20 ip4:198.2.128.0/18 ~all";

 $regexIpAddress = '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/';        
 preg_match_all($regexIpAddress, $spfreccord, $ip_match);
 var_dump($ip_match);

Gives:

array(1) {
  [0]=>
  array(5) {
    [0]=>
    string(14) "46.163.100.196"
    [1]=>
    string(14) "46.163.100.194"
    [2]=>
    string(12) "85.13.135.76"
    [3]=>
    string(16) "205.201.128.0/20"
    [4]=>
    string(14) "198.2.128.0/18"
  }
}



回答2:


You want preg_match_all(), and a slight modification of your regex:

php >  $regexIpAddress = '/ip4:([0-9.]+)/';
php >  preg_match_all($regexIpAddress, $spfreccord, $ip_match);
php >  var_dump($ip_match[1]);
array(3) {
  [0]=>
  string(14) "46.163.100.196"
  [1]=>
  string(14) "46.163.100.194"
  [2]=>
  string(12) "85.13.135.76"
}
php >

You don't need to match against a-z; it's not a valid part of an IP address, 4 or 6. Since you said you only want IPv4, I've excluded any matching of IPv6 addresses.

If you wanted to include IPv6 as well, you can do this:

php > $regexIpAddress = '/ip[46]:([0-9a-f.:]+)/';
php > preg_match_all($regexIpAddress, $spfreccord, $ip_match);
php > var_dump($ip_match[1]);
array(4) {
  [0]=>
  string(14) "46.163.100.196"
  [1]=>
  string(14) "46.163.100.194"
  [2]=>
  string(12) "85.13.135.76"
  [3]=>
  string(39) "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
}


来源:https://stackoverflow.com/questions/37640920/regex-to-extract-only-ipv4-addresses-from-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!