编程语言
首页 > 编程语言> > php – 正则表达式只从文本中提取IPv4地址

php – 正则表达式只从文本中提取IPv4地址

作者:互联网

我试图从给定的示例输入中仅提取IP地址,但它会用它提取一些文本.这是我的代码:

$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);

我希望在表的每一列中只匹配IPv4 IP地址xxx.xxx.xxx.xxx,但看起来$regexIpAddress不正确.

能帮我找到正确的正则表达式来提取IPv4 IP地址吗?谢谢.

解决方法:

使用以下正则表达式:

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

所以对此:

$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);

得到:

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"
  }
}

标签:php,regex,ip,spf
来源: https://codeday.me/bug/20190829/1757946.html