Reputation: 37
I want to add to every IP address from array +1 number. I know about bcadd();
but I can't make it work as every IP address has different length and I just need to increase the last number of it.
For example:
array("194.32.14.152", "4.189.23.35", etc...);
... would become:
array("194.32.14.153", "4.189.23.36", etc...);
Now maybe I need to apply str_pad();
to match the last dot?
Any help would be appreciated.
Upvotes: 2
Views: 642
Reputation: 48101
preg_replace_callback()
, IMO, is the most succinct and appropriate approach. When there is a single, native function that does it all, why do anything else?
Match the final sequence of digits and so long as it is not 255
, increment the substring.
Code: (Demo)
$ips = ["194.32.14.199", "4.189.23.35", "4.189.23.255"];
var_export(preg_replace_callback('~\d+$(?<!255)~',
function($m) {
return ++$m[0];
},
$ips)
);
From PHP7.4+, the syntax becomes more brief by way of arrow syntax.
var_export(preg_replace_callback('~\d+$(?<!255)~', fn($m) => ++$m[0], $ips));
Both snippets produce:
array (
0 => '194.32.14.200',
1 => '4.189.23.36',
2 => '4.189.23.255',
)
The pattern:
\d+ #match 1 or more digits
$ #match the end of the string
(?<!255) #lookbehind to ensure the matched number is not literally 255
In using this pattern, you do not bother handling 255
, and you increment all other numbers that are matched.
Upvotes: 2
Reputation: 7533
Another solution using built-in ip2long and long2ip and PHP bitwise operators
<?php
$ips = array("194.32.14.152", "4.189.23.35", "4.51.11.255");
$newIps = [];
foreach($ips as $ipString){
$ip = ip2long($ipString);
$lastByte = ($ip & 0x000000FF)+1;
$lastByte = $lastByte > 255 ? 255 : $lastByte;
$newIps[]= long2ip(( $lastByte ) | (0xFFFFFF00 & $ip ) );
}
var_dump($newIps);
This outputs
array(3) {
[0]=>
string(13) "194.32.14.153"
[1]=>
string(11) "4.189.23.36"
[2]=>
string(11) "4.51.11.255"
}
Live demo https://3v4l.org/iZeAR
Upvotes: 1
Reputation: 50974
You can map your array to your new IP addresses. In the map
method, you can split the current string by .
using explode()
. Then, to get the last number from your IP you can use array_pop
, which you can then cast to an integer so that you can add one to it. You can then array_push()
this updated value onto your parts array, and join each part in your array back together using implode()
.
See example below:
$arr = array("194.32.14.152", "4.189.23.35", "4.189.23.255");
$res = array_map(function($v) { // Example, let $v = "194.32.14.152";
$parts = explode('.', $v); // "194.32.14.152" -> ["194", "32", "14", "152"];
array_push($parts, min((int) array_pop($parts)+1, 255)); // ["194", "32", "14", 153]
return implode('.', $parts); // "194.32.14.153"
}, $arr);
print_r($res); // ["194.32.14.153", "4.189.23.36", "4.189.23.255"]
Upvotes: 1