Jump to content


Photo

Validate a MAC Address


  • Please log in to reply
3 replies to this topic

#1 SharkBait

SharkBait
  • Members
  • PipPipPip
  • Advanced Member
  • 845 posts
  • LocationMetro Vancouver, BC

Posted 07 July 2006 - 07:06 PM

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:

<?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";
}
?>

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?

#2 shoz

shoz
  • Staff Alumni
  • Advanced Member
  • 600 posts

Posted 07 July 2006 - 07:52 PM

You can try the following
/^(?:[0-9a-fA-F]{2}[:;.]?){6}$/
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.
/^[0-9a-fA-F]{2}(?=([:;.]?))(?:\\1[0-9a-fA-F]{2}){5}$/


#3 SharkBait

SharkBait
  • Members
  • PipPipPip
  • Advanced Member
  • 845 posts
  • LocationMetro Vancouver, BC

Posted 07 July 2006 - 08:41 PM

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!

#4 shoz

shoz
  • Staff Alumni
  • Advanced Member
  • 600 posts

Posted 08 July 2006 - 03:18 AM

/^[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.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users