note 57541 added to function.preg-match
| From: | 1413 at blargh dot com | Date: | Thu, 06 Oct 2005 20:41:46 +0000 |
| Subject: | note 57541 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-96531@lists.php.net to get a copy of this message | ||
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
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+57541
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+57541&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+57541&report=yes
Search -- http://master.php.net/manage/user-notes.php