Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

A combination of str_replace and preg_replace:

$str = preg_replace('~..(?!$)~', '\0:', str_replace(".", "", $str));

First stripping out the . then adding : after .. two of any characters (?!$) if not at the end.

Test at eval.in


Or use a capture group and do it without str_replace:

$str = preg_replace('~(..)(?!$)\.?~', '\1:', $str);

Test at regex101.com

There's not much difference in performance.

like image 74
Jonny 5 Avatar answered Sep 04 '26 19:09

Jonny 5


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

like image 43
Tibor B. Avatar answered Sep 04 '26 18:09

Tibor B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!