Convert MAC Address Format

自闭症网瘾萝莉.ら 提交于 2019-12-05 20:14:06

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.

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

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

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!