'Convert MAC Address Format

I just wrote a small script to pull hundreds of MAC Addresses from a switch for comparison, however they are formatted as "0025.9073.3014" rather than the standard "00:25:90:73:30:14".

I am stumped on how to convert this, where the best I can come up with is exploding these into pieces at the ".", then breaking them down further into 2 pieces each, then rejoin all parts with ":" separators.

I am okay with hacky methods but this is bothering me because that is a very poor approach. Is there any way to perform this better?



Solution 1:[1]

If you don't like regular expressions, then here's another method of doing it, which is more understandable, if you're new to PHP. Basically, it just removes the dots, and then splits the string into an array after every 2 characters, then implodes them with a colon:

$string = "0025.9073.3014";
$result = implode(":", str_split(str_replace(".", "", $string), 2));
echo $result;

Outputs:

00:25:90:73:30:14

Solution 2:[2]

Using preg_replace with capturing groups, backreferences:

$mac = "0025.9073.3014";
$mac = preg_replace('/(..)(..)\.(..)(..)\.(..)(..)/',
                    '$1:$2:$3:$4:$5:$6', $mac);
echo($mac);
// => 00:25:90:73:30:14

Solution 3:[3]

Another option, if the mac address is constant in this format.

$str = '0025.9073.3014';
$str = preg_replace('~\d+\K(?=\d\d)|\.~', ':', $str);
echo $str; //=> "00:25:90:73:30:14"

Solution 4:[4]

This universal function uses sscanf to parse the string and vsprintf to format the output.

function formatMac($string,$formatInput,$formatOutput)
{
  return vsprintf($formatOutput,sscanf($string,$formatInput));
}

Examples of usage:

$string = "0025.9073.3014";
echo formatMac($string,'%02s%02s.%02s%02s.%02s%02s','%02s:%02s:%02s:%02s:%02s:%02s');
//00:25:90:73:30:14

$string = '00:a0:3d:08:ef:63';
echo formatMac($string,'%x:%x:%x:%x:%x:%x','%02X%02X%02X:%02X%02X%02X');
//00A03D:08EF63

$string = '00A03D:08EF63';
echo formatMac($string,'%02X%02X%02X:%02X%02X%02X','%02x:%02x:%02x:%02x:%02x:%02x');
//00:a0:3d:08:ef:63

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tibor B.
Solution 2
Solution 3 hwnd
Solution 4 jspit