note 57541 deleted from function.preg-match by colder

From: Date: Mon, 18 Jun 2007 18:27:20 +0000
Subject: note 57541 deleted from function.preg-match by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-127613@lists.php.net to get a copy of this message
Note Submitter: 1413 at blargh dot com ---- For a system I'm writing, I get MAC addresses in a huge number of formats. I needed something to handle all of the following: 0-1-2-3-4-5 00:a0:e0:15:55:2f 89 78 77 87 88 9a 0098:8832:aa33 bc de f3-00 e0 90 00e090-ee33cc ::5c:12::3c 0123456789ab and more. The function I came up with is: <?php function ValidateMAC($str) { preg_match("/^([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[- : ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})$/", $str, $arr); if(strlen($arr[0]) != strlen($str)) return FALSE; return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", hexdec($arr[1]), hexdec($arr[2]), hexdec($arr[3]), hexdec($arr[4]), hexdec($arr[5] ), hexdec($arr[6])); } $testStrings = array("0-1-2-3-4-5","00:a0:e0:15:55:2f","89 78 77 87 88 9a","0098:8832:aa33","bc de f3-00 e0 90","00e090-ee33cc"," bf:55:6e:7t:55:44", "::5c:12::3c","0123456789ab"); foreach($testStrings as $str) { $res = ValidateMAC($str); print("$str => $res<br>"); } ?> This returns: 0-1-2-3-4-5 => 00:01:02:03:04:05 00:a0:e0:15:55:2f => 00:A0:E0:15:55:2F 89 78 77 87 88 9a => 89:78:77:87:88:9A 0098:8832:aa33 => 00:98:88:32:AA:33 bc de f3-00 e0 90 => BC:DE:F3:00:E0:90 00e090-ee33cc => 00:E0:90:EE:33:CC bf:55:6e:7t:55:44 => ::5c:12::3c => 00:00:5C:12:00:3C 0123456789ab => 01:23:45:67:89:AB

« previous php.notes (#127613) next »