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
Share on other sites

You can try the following
[code]
/^(?:[0-9a-fA-F]{2}[:;.]?){6}$/
[/code]
This will allow for different delimiters however.
eg: 00;00.0000:00.00

For the delimiter to be the same throughout, you can try this.
[code]
/^[0-9a-fA-F]{2}(?=([:;.]?))(?:\\1[0-9a-fA-F]{2}){5}$/
[/code]
Link to comment
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.