Reputation: 21660
I have a mssql database in which my primary keys are GUIDs. I am working on a web interface for inserting some data. I need a GUID, generated by php. I am using com_create_guid()
function. So, before trying to insert I want to ensure that my parameters are valid. I can not find a way to check if a string(com_create_guid()
returns string) is a valid GUID.
Upvotes: 29
Views: 25470
Reputation: 547
There are a few rules that should be imposed on the UUID/GUID pattern.
Simplified patterns
Expression:
var_dump(
preg_match("/^(\{)?[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}(?(1)\})$/i", $guid)
? "ok", "not ok");
Translation:
Upvotes: 48
Reputation: 401032
Considering a GUID is defined as something like this : "A98C5A1E-A742-4808-96FA-6F409E799937" (from what the wikipedia page says)
I suppose using a regex like this one would do :
$guid = 'A98C5A1E-A742-4808-96FA-6F409E799937';
if (preg_match('/^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$/', $guid)) {
var_dump('ok');
} else {
var_dump('not ok');
}
It will match for
Each set of characters being separated by a '-
'
Considering you're using com_create_guid
, the regex check for optionnals }
and {
arround the guid, which means this would display 'ok' too :
$guid = '{A98C5A1E-A742-4808-96FA-6F409E799937}';
if (preg_match('/^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$/', $guid)) {
var_dump('ok');
} else {
var_dump('not ok');
}
Upvotes: 37