简体   繁体   中英

IPv4 RegEx in PHP is not matching the IPs with last octet being 3 digit

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.

Your regexp looks wrong as follows-

在此处输入图片说明

You need this-

^([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}))$

正则表达式可视化

You can test the validity of any IP address using this rule here : Debuggex Demo

Reverse the alternate order to try 3 digits first:

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])

If ([1-9])?[0-9] comes first, it may match 12 in 123 and ignores the other alternate.

try this find only valid 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);

output

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

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM