0

I have a regex ** **

I am using preg_match_all method in PHP to match the Ips. But it doesn't match the IP if the last octet is 3 digits. Plz can anyone help me and let me know where I am going wrong.

Code is like:

$tnlip_regex = "/(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])[\.])(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])[\.])(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])[\.])(([1-9]?\d|1\d\d|2[0-4]\d|25[0-5]))/";
preg_match_all($tnlip_regex, $row_data, $tnlip_matches);

$row_data is the data from where I am finding IPs. $tnlip_matches is the array where I am putting them.

4

3 回答 3

1

您的正则表达式看起来错误如下 -

在此处输入图像描述

你需要这个-

^([0-9]|[1-9][0-9]|(1[0-9]{2}|2[0-5]{2}))\.([0-9]|[1-9][0-9]|(1[0-9]{2}|2[0-5]{2}))\.([0-9]|[1-9][0-9]|(1[0-9]{2}|2[0-5]{2}))$

正则表达式可视化

您可以在此处使用此规则测试任何 IP 地址的有效性:Debuggex Demo

于 2013-12-21T06:17:34.307 回答
0

颠倒交替顺序以先尝试 3 位数字:

http://regex101.com/r/nN4qG7

((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|([1-9])?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|([1-9])?[0-9])

如果([1-9])?[0-9]先出现,它可能会匹配12123忽略另一个备用。

于 2013-05-06T07:04:58.000 回答
0

试试这个发现只有有效的ip

  $row_data='10.168.3.344  10.168.3.244 192.168.0.244';
  $tnlip_regex = "#[0-9]+.[0-9]+.[0-9]+.[0-9]+#";
  preg_match_all($tnlip_regex, $row_data, $tnlip_matches);
  foreach($tnlip_matches[0] as $Key=>$Val){
     if(!filter_var($Val, FILTER_VALIDATE_IP)){//check for valid ip
        unset($tnlip_matches[0][$Key]);
     }
   }
   print_r($tnlip_matches);

输出

 Array
(
   [0] => Array
    (
        [1] => 10.168.3.244
        [2] => 192.168.0.244
    )

)
于 2013-05-06T07:13:01.683 回答