在PHP中增加/减少字符串中的MAC地址

时间:2013-08-22 03:03:07

标签: php regex

我有一个字符串形式的mac地址。我有兴趣获取Mac字符串并将其增加/减少1值,同时保持PHP的完整性

Ex:00:A1:2C:3B:99:1F

-1:00:A1:2C:3B:99:1E +1:00:A1:2C:3B:99:20

2 个答案:

答案 0 :(得分:3)

将十六进制转换为十进制并返回

$hexstring = "00:A1:2C:3B:99:1F";
$hex = preg_replace("/:/", '', $hexstring);

$dec = hexdec($hex);
$dec--; //or ++

$hex = dechex($dec);

$hexstring = implode(":", str_split($hex, 2));

答案 1 :(得分:0)

<强>测试

<?php
$hexval="00:A1:2C:3B:99:1F";

//First 10 MAC Address Increments
for($i=0;$i<10;$i++)
{
    $dec=hexdec($hexval);
    $dec++;
    $hexval=dechex($dec);
    $hexval=rtrim(strtoupper(chunk_split($hexval, 2, ':')),':');
    echo "00:A1:{$hexval}<br>";
}
echo "<br><br>";
//First 10 MAC Address Decrements
$hexval="00:A1:2C:3B:99:1F";
for($i=0;$i<10;$i++)
{
    $dec=hexdec($hexval);
    $dec--;
    $hexval=dechex($dec);
    $hexval=rtrim(strtoupper(chunk_split($hexval, 2, ':')),':');
    echo "00:A1:{$hexval}<br>";
}

输出:

00:A1:2C:3B:99:20
00:A1:2C:3B:99:21
00:A1:2C:3B:99:22
00:A1:2C:3B:99:23
00:A1:2C:3B:99:24
00:A1:2C:3B:99:25
00:A1:2C:3B:99:26
00:A1:2C:3B:99:27
00:A1:2C:3B:99:28
00:A1:2C:3B:99:29


00:A1:2C:3B:99:1E
00:A1:2C:3B:99:1D
00:A1:2C:3B:99:1C
00:A1:2C:3B:99:1B
00:A1:2C:3B:99:1A
00:A1:2C:3B:99:19
00:A1:2C:3B:99:18
00:A1:2C:3B:99:17
00:A1:2C:3B:99:16
00:A1:2C:3B:99:15