Search code examples
phpstringformattinguuiddelimited

Format 32-character string with hyphens to become UUID


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';

Solution

  • <?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;