简体   繁体   English

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

[英]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. 我在PHP中使用preg_match_all方法来匹配Ips。 But it doesn't match the IP if the last octet is 3 digits. 但是,如果最后一个八位字节为3位数字,则与IP地址不匹配。 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. $row_data是从中找到IP的数据。 $tnlip_matches is the array where I am putting them. $tnlip_matches是我放置它们的数组。

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 您可以在此处使用此规则测试任何IP地址的有效性: Debuggex演示

Reverse the alternate order to try 3 digits first: 颠倒替代顺序,先尝试3位数字:

http://regex101.com/r/nN4qG7 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. 如果首先出现([1-9])?[0-9] ,则它可能与123中的12匹配,并忽略另一个替代项。

try this find only valid ip 试试这个找到唯一有效的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
    )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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