PHP: Mac address validating and formatting
There are three common tasks related to storing mac address in the database as char(12) (it is feasible to use bigint instead but in our case we opted for a text type).
1. Validating mac address entered by user.
In our case user is allowed to enter mac address the way s/he wants:
000CF15698AD
00:0C:F1:56:98:AD
00-0C-F1-56-98-AD
So the perfect solution would be to apply regular expression like this one:
/([a-fA-F0-9]{2}[:|\-]?){6}/
For example, in plain PHP:
public static function IsValid($mac) { return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $mac) == 1); } |
or using Zend Framework:
public static function IsValid($mac) { $validator = new Zend_Validate_Regex('/([a-fA-F0-9]{2}[:|\-]?){6}/'); return $validator->isValid($mac); } |
2. Remove separating symbols ‘:’ or ‘-‘ from the mac address to fit only 12 character storage.
This is really easy to implement using str_replace().
public static function RemoveSeparator($mac, $separator = array(':', '-')) { return str_replace($separator, '', $mac); } |
3. Adding separating symbol ‘:’ back when the mac address is displayed to a user.
This could look a bit ugly if the straight forward solution is applied, e.g. something like below:
public static function AddSeparator($mac, $separator = ':') { $result = ''; while (strlen($mac) > 0) { $sub = substr($mac, 0, 2); $result .= $sub . $separator; $mac = substr($mac, 2, strlen($mac)); } // remove trailing colon $result = substr($result, 0, strlen($result) - 1); } |
So I kept looking for more elegant solution. Ideally I was hoping for one-line solution. And the magic comes with function str_split():
public static function AddSeparator($mac, $separator = ':') { return join($separator, str_split($mac, 2)); } |