SharkBait Posted July 7, 2006 Share Posted July 7, 2006 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:0000;00;00;00;00;0000.00.00.00.00.000000000000Where 00 must be within A-Z 0-9 case insensitive. What am I doing wrong? Quote Link to comment Share on other sites More sharing options...
shoz Posted July 7, 2006 Share Posted July 7, 2006 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.00For 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] Quote Link to comment Share on other sites More sharing options...
SharkBait Posted July 7, 2006 Author Share Posted July 7, 2006 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! Quote Link to comment Share on other sites More sharing options...
shoz Posted July 8, 2006 Share Posted July 8, 2006 /^[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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.