PHP中的IPv4 RegEx与最后一个八位字节为3位的IP不匹配

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.

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
    )

)

Your regexp looks wrong as follows-

enter image description here

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

Regular expression visualization

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