簡體   English   中英

PHP中的IPv4 RegEx與IP地址不匹配,最后一個八位字節為3位數字

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

我有一個正則表達式** **

我在PHP中使用preg_match_all方法來匹配Ips。 但是,如果最后一個八位字節為3位數字,則與IP地址不匹配。 請誰能幫助我,讓我知道我要去哪里錯了。

代碼就像:

$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是從中找到IP的數據。 $tnlip_matches是我放置它們的數組。

您的正則表達式看起來錯誤如下:

在此處輸入圖片說明

你需要這個-

^([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演示

顛倒替代順序,先嘗試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] ,則它可能與123中的12匹配,並忽略另一個替代項。

試試這個找到唯一有效的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
    )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM