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';
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Vanture
  • 65
  • 5

3 Answers3

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;
fico7489
  • 7,931
  • 7
  • 55
  • 89
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;
James
  • 20,957
  • 5
  • 26
  • 41
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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136