【问题标题】:Regex to extract only IPv4 addresses from text正则表达式仅从文本中提取 IPv4 地址
【发布时间】:2016-06-05 10:36:51
【问题描述】:

我尝试从给定的示例输入中仅提取 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}/?
  • 是的,它工作得很好,但一个小问题是我无法提取 cidr 类 v=spf1 ip4:205.201.128.0/20 ip4:198.2.128.0/18 吗?是否可以提取 cidr 205.201.128.0/20
  • 然后改成:/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/
  • 嗨@Will 你的回答工作正常,但我不需要用ips 提取文本“ip4”,嗨@Thamilan 你的回答对我很好,但一个问题是我不能像这样提取类 cidr 198.2.128.0/18 所以请如果有什么要添加到我的 ipregex 来提取像这样的 cidr 示例 198.2.128.0/18 谢谢大家
  • @sala.eddi 我的不提取文本,只提取 IP。查看我的示例中的输出。

标签: php regex ip spf


【解决方案1】:

使用以下正则表达式:

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

【讨论】:

    【解决方案2】:

    您想要preg_match_all(),并对您的正则表达式稍作修改:

    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 >
    

    你不需要匹配a-z;它不是 IP 地址的有效部分,4 或 6。既然你说你只想要 IPv4,我已经排除了任何匹配的 IPv6 地址。

    如果您也想包含 IPv6,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2016-01-31
      • 2018-02-27
      • 1970-01-01
      • 2011-01-18
      • 2011-07-14
      • 2012-12-01
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多