Validating the format of a universally unique identifier

Here’s a function to validate the format of a universally unique identifier, or UUID:

function uuid_is_valid( $uuid ) {

    // check string length
    if( strlen( $uuid ) != 36 ) return false; // no good

    // check formatting
    return preg_match( '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/i', $uuid ) ? true : false;


It’s expecting a 36-character UUID. Adjust this length if necessary depending on the expected UUID length (e.g. with hyphens vs without).

It returns a Boolean, so it would be integrated like so:

if( uuid_is_valid() ) {
    // do something
} else {
    // do something else

Note that this only checks a UUID’s formatting and not whether the UUID exists or not.