php-regexHow to use PHP regex to match UUID?
A UUID (Universally Unique Identifier) is a 128-bit number used to identify information in computer systems. To match a UUID with a regular expression in PHP, you can use the following code:
$uuid = '123e4567-e89b-12d3-a456-426655440000';
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $uuid)) {
echo 'Valid UUID';
} else {
echo 'Invalid UUID';
}
Output example
Valid UUID
The code consists of the following parts:
-
$uuid = '123e4567-e89b-12d3-a456-426655440000';
- This is the UUID that we are trying to match. -
preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $uuid)
- This is the regular expression used to match the UUID. It consists of five parts, each of which is enclosed in square brackets and followed by a number in curly braces. The first part matches any 8 hexadecimal digits, the second part matches any 4 hexadecimal digits, the third part matches any 4 hexadecimal digits, the fourth part matches any 4 hexadecimal digits, and the fifth part matches any 12 hexadecimal digits. -
if (preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $uuid)) {
- This is the if statement that checks if the regular expression matches the UUID. -
echo 'Valid UUID';
- This is the code that is executed if the regular expression matches the UUID. -
echo 'Invalid UUID';
- This is the code that is executed if the regular expression does not match the UUID.
Helpful links
More of Php Regex
- How to use PHP regex to match an exact string?
- How to match a single quote in PHP regex?
- How to get last matched occurrence in PHP regex?
- How to match a double quote in PHP regex?
- How to use PHP regex to match a boolean value?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to match a space using PHP regex?
- How to remove all non-numeric characters using PHP regex?
See more codes...