开发者

PHP preg_split IPs in a string

开发者 https://www.devze.com 2023-02-13 00:50 出处:网络
I am trying to use preg_split in PHP to break up the following string and return me the 2 ip addresses:

I am trying to use preg_split in PHP to break up the following string and return me the 2 ip addresses:

$membersStr = "members { 167.69.27.151:4449 {} 167.69.27.153:4449 {} 167.69.27.154:4449 { session user disabled } 167.67.27.156:4449 }";

My code is:

$nodesArray = preg_split("/\b(25[0-5]|2[0-4][0-9]|[01]?[0-开发者_Python百科9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/", $membersStr, -1, PREG_SPLIT_NO_EMPTY);

then simply print it for now:

print_r($nodesArray);

However it is an empty array. I double checked my regular expression from an online checker and it returns the IP.

Trying :

preg_match_all('/\d+\.\d+\.\d+\.\d+/', $membersStr, $nodesArray);
echo $nodesArray[0];

Prints:

Array

In my browser.


You don't need that complex of a Regex here. Use this Regex to pluck out the IPs inside the first set of brackets:

members \{(.*)\}

Take the first group (what is between the parentheses). Then explode() on {} to get each IP. Iterate over each value, trim it, and make sure it isn't blank.

Edit

Try this:

$membersStr = "members { 167.69.27.151:4449 {} 167.69.27.153:4449 {} }";

$ips = explode("{", $membersStr, 2);
$ips = explode("{}", $ips[1]);

foreach ($ips as $ip){
    $ip = trim($ip);
    if ($ip != "" && $ip != "}")
        echo $ip . "<br/>";
}

SAMPLE PULLED FROM FILE

 members {
      167.69.97.48:4440 {
         session user disabled
      }
      167.69.97.91:4440 {}
   }

Edit

Use the other answer, but like this:

$membersStr = @" members {
      167.69.97.48:4440 {
         session user disabled
      }
      167.69.97.91:4440 {}
   }";

preg_match_all('/\d+\.\d+\.\d+\.\d+/', $membersStr, $nodesArray);

foreach ($nodesArray[0] as $ip)
    echo $ip . "<br/>";


If you use your existing regular expression for splitting, then the matched part will certainly not part of the result list. Instead you'll get the empty space and fill stuff in between.

Therefore it's simpler if you match and extract the parts that you actually want:

preg_match_all('/\d+\.\d+\.\d+\.\d+/', $str, $matches);
$list = $matches[0];
0

精彩评论

暂无评论...
验证码 换一张
取 消