Regular Expressions + Mac Address (php)

Associate
Joined
3 Oct 2006
Posts
2,304
Location
London
Hi,

I'm writing some basic forms for work, for collecting data, and I am just onto validating my forms now. One of the fields is Mac Address. I'm no expert on php and a colleague at work told me about regular expressions. Excellent I thought, I did some reading and came up with the following :

PHP:
<?php

$mac = "00:19:e3:01:56:47";

if (eregi("$([a-z0-9]{2})\:{5}([a-z0-9]{2})^", $mac, $mac_add)) {
	
	echo $mac;
	
} else {
	
	echo "Invalid mac address: $mac";
	
}




?>

However it doesn't work.... I can't seem to get it to work. I've even tried some other "pre-made" expressions, for mac address', but they don't work either

Sitepoint : Suppost to validate with either ":" or "-"

PHP:
(?<![-0-9a-f:])([\da-f]{2}[-:]){5}([\da-f]{2})(?![-0-9a-f:])

Have I done anything stupid either with my simple if statement or is my expression wrong?

Any help would be greatly appreciated!

JB
 
The following works on my test system:

Code:
<?php 
$mac = "00:19:e3:01:56:47"; 
if (eregi("^([0-9A-F]{2}:){5}[0-9A-F]{2}$", $mac, $mac_add)) { 
  echo "Valid mac address: $mac"; 
} 
else { 
  echo "Invalid mac address: $mac";
} 
?>
As a test, try:

http://www.riddlermarc.co.uk/test/valid_mac.php
http://www.riddlermarc.co.uk/test/invalid_mac.php

Both use the same code as above but the $mac value on the second page is intentionally dodgy :)



Technically speaking, you don't need the ^ and $:
^ Matches the start of the line (or any line, when applied in multiline mode)
$ Matches the end of the line (or any line, when applied in multiline mode)

http://en.wikipedia.org/wiki/Regular_expression
http://www.riddlermarc.co.uk/test/mac.php works just fine without :)
 
Last edited:
Ah cheers, for that, your changed reg exp showed me what was wrong with mine!

I had the ^ and $ the wrong way around and I had the {5} inside the brackets while the : was outside the brackets (for the initial part of the reg exp).

Here is the new improved, working version!

PHP:
<?php

$mac = "00:19:e3:01:56:47";

if (eregi("^([0-9A-F]{2}:){5}([0-9A-F]{2})$", $mac, $mac_add)) {
	
	echo $mac_add[0];
	
} else {
	
	echo "Invalid mac address: $mac";
	
}

?>
 
Back
Top Bottom