Jump to content

Validate a MAC Address


SharkBait

Recommended Posts

Hi,

I'm trying to figure out my regex for validating a MAC address. I obviously have it wrong but this is what I have:

[code]
<?php
$mac = "00:00:00:00:00:00";

if(preg_match('/^[A-F0-9.:;]{2}+\.[A-F0-9.:;]{2}+\.[A-F0-9.:;]{2}+\.[A-F0-9.:;]{2}+\.[A-F0-9.:;]{2}\.[A-F0-9.:;]{2}$/i', $mac)) {
  echo "MAC is valid";
} else {
  echo "MAC IS INVALID";
}
?>
[/code]

I want to match:
00:00:00:00:00:00
00;00;00;00;00;00
00.00.00.00.00.00
0000000000
Where 00 must be within A-Z 0-9 case insensitive.  What am I doing wrong?
Link to comment
https://forums.phpfreaks.com/topic/13974-validate-a-mac-address/
Share on other sites

The last one does what I want it to.

Thanks :)

Lets see if I can explain this to myself.

[0-9a-fA-f]{2}  Matches 2 characters in a hex type manor
(?=([:;.])))    Matches the delimeter inbetween the 2 digit groupings
(?:\\1[0-9a-fA-F]{2}){5}  I assume this checks that there are upto 6 two character groupings?

I guess the last little bit I am a bit foggy on.  But it does work which is cool!
Link to comment
https://forums.phpfreaks.com/topic/13974-validate-a-mac-address/#findComment-54546
Share on other sites

/^[0-9a-fA-F]{2}(?=([:;.]?))(?:\\1[0-9a-fA-F]{2}){5}$/

^ => Match the beginning of the string

[0-9a-fA-F]{2} => Match the hexadecimal value

(?=([:;.]?)) => Lookahead (?=) and try to match the first delimiter (:;.). Storing the value matched in a backreference. You'll note the [:;.] is inside "()" to capture the matched value. The "?" means matching the [:;.] is optional.

(?:\\1[0-9a-fA-F]{2}){5} => surrounding a pattern in () means group and capture the matched pattern in a backreference. The ?: following the opening "(" means don't capture the pattern matched. Only group it.

The \\1 holds the value of the 1st backreference. In this case the delimiter. We try to match the delimiter we first matched then a hexadecimal value 5 times ({5}).

$ => matches the end of the string.
Link to comment
https://forums.phpfreaks.com/topic/13974-validate-a-mac-address/#findComment-54668
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.