Last active
March 6, 2024 22:26
-
-
Save Joel-James/3a6201861f12a7acf4f2 to your computer and use it in GitHub Desktop.
Check if UUID is in valid format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check if a given string is a valid UUID | |
* | |
* @param string $uuid The string to check | |
* @return boolean | |
*/ | |
function isValidUuid( $uuid ) { | |
if (!is_string($uuid) || (preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', $uuid) !== 1)) { | |
return false; | |
} | |
return true; | |
} |
Could leave the '=== 1' off too.
@ellisgl without comparing don't have a Boolean return.
preg_match returns 0, 1, false
Ah, that's right.. ugh.
Thank you ellisgl. Your method works perfectly for me.
@impressto You're welcome.
/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i
@ellisgl works wonderfully - thank you
@cakebake You're welcome.
great gist, I come up with this
return $uuid && preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', $uuid);
/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i
Excelent!! It works fine.
Perfect!
Updated based on @ellisgl suggestion
🤩
One line :)
/**
* Check if a given string is a valid UUID
*
* @param mixed $uuid The string to check
* @return boolean
*/
function isValidUuid(mixed $uuid): bool
{
return is_string($uuid) && preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', $uuid);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not just
return (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid) === 1);
It's return false isn't a string and the string need to be a UUID.
This means less processing even if it's just a few cycles.