Format 32-character string with hyphens to become UUID
Asked Answered
G

3

5

I am receiving a UUID value from an external source, but the string doesn't contain any hyphens.

A valid UUID should be in the format:

abcdef01-2345-6789-abcd-ef0123456789

How can I convert:

$UUID = '42f704ab4ae141c78c185558f9447748';

To:

$UUID = '42f704ab-4ae1-41c7-8c18-5558f9447748';
Guacharo answered 2/11, 2015 at 18:49 Comment(0)
J
11
<?php 

//$UUID = 42f704ab-4ae1-41c7-8c18-5558f944774
$UUID = "42f704ab4ae141c78c185558f9447748";


$UUID = substr($UUID, 0, 8) . '-' . substr($UUID, 8, 4) . '-' . substr($UUID, 12, 4) . '-' . substr($UUID, 16, 4)  . '-' . substr($UUID, 20);
echo $UUID;
Jdavie answered 2/11, 2015 at 18:55 Comment(0)
B
11

Here's another way:

$input = "42f704ab4ae141c78c185558f9447748";
$uuid = preg_replace("/(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})/i", "$1-$2-$3-$4-$5", $input);
echo $uuid;
Bahamas answered 2/11, 2015 at 18:59 Comment(1)
The case-insensitive flag on this pattern is useless because \w is already case-insensitive.Geulincx
G
1

Similar to this answer which formats digital strings to hyphenated phone numbers, you can sensibly use preg_replace() or a combination of sscanf() with a joining function.

Code: (Demo) (or no character classes)

$UUID = "f9e113324bd449809b98b0925eac3141";

echo preg_replace('/(?:^[\da-f]{4})?[\da-f]{4}\K/', '-', $UUID, 4);

echo "\n---\n";

vprintf('%s-%s-%s-%s-%s', sscanf($UUID, '%8s%4s%4s%4s%12s'));

echo "\n---\n";

echo implode('-', sscanf($UUID, '%8s%4s%4s%4s%12s'));

Output:

f9e11332-4bd4-4980-9b98-b0925eac3141
---
f9e11332-4bd4-4980-9b98-b0925eac3141
---
f9e11332-4bd4-4980-9b98-b0925eac3141
Geulincx answered 16/7, 2022 at 13:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.