Jump to content

[SOLVED] Regex Expression


kmaid

Recommended Posts

Hello I could use some help with regex validating a string. The string is hexadecimal (uses 0-9 a-f character set) and 36 characters long broken up with dashes into 5 sections eg:

 

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

 

Here are some examples of valid keys:

 

a822ff2b-ff02-461d-b45d-dcd10a2de0c2

f63f298d-0989-49ff-8aa3-5897e259e767

8e589107-5f97-4e60-8194-11fcda76c194

c428132b-fd96-4b34-9bbe-9e627a5a50e4

2ceb9b3e-cf25-446b-b04a-dccae9d0a77a

 

A regex expression that can validate the correct character set, format and number of characters would be very helpful and be interesting to compare against what I am playing with.

 

Thanks

Kmaid

 

Link to comment
https://forums.phpfreaks.com/topic/126997-solved-regex-expression/
Share on other sites

Try this out:

 

<?php
$tests = array(
	"a822ff2b-ff02-461d-b45d-dcd10a2de0c2",
	"f63f298d-0989-49ff-8aa3-5897e259e767",
	"8e589107-5f97-4e60-8194-11fcda76c194",
	"c428132b-fd96-4b34-9bbe-9e627a5a50e4",
	"2ceb9b3e-cf25-446b-b04a-dccae9d0a77a",
	"2ceb9b7e-cf25-421b-b04a-dccae9d0a77z",
	);

foreach($tests as $t){
if(preg_match("#[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}#i", $t)){
	echo $t . ": <b>Valid</b><br />";
}else{
	echo $t . ": <b>Invalid</b><br />";
}
}
?>

I think you would want to check the whole string only - i.e. add ^ and $ (and the D modifier) to the regex. Else something like "#¤%&/a822ff2b-ff02-461d-b45d-dcd10a2de0c2" will pass.

 

	if(preg_match("#^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$#iD", $t)){

When you have repeating sub-patterns (such as -[\da-f]{4}) which in this case is repeated 3 times, you can use recursive expressions. The idea is simple... after the first capture in parenthesis, you can 'reuse' this capture which effectively shortens and simplifies the code from a readability standpoint:

 

#^[\da-f]{8}(-[\da-f]{4})(?1)(?1)-[\da-f]{12}$#

 

Cheers,

 

NRG

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.