PHP.GT

Parsing existing ULIDs

In a real application, we often receive an identifier long after it was first created.

That might be from:

  • a database row
  • a route parameter
  • an API payload
  • a message queue
  • a log line we want to inspect

This library gives us two ways to work backwards from the string.

Option 1: reconstruct an Ulid object

If we want the full helper API again, construct a new object with init:

use GT\Ulid\Ulid;

$string = "ORDER_01KPKT4PFTKVQ9P1E72F";
$id = new Ulid(init: $string);

echo $id->getPrefix(), PHP_EOL;
echo $id->getTimestampString(), PHP_EOL;
echo $id->getRandomString(), PHP_EOL;

This is the most natural choice when our codebase already expects an Ulid object.

Option 2: use Extractor

If we only need one section, Extractor is more direct:

use GT\Ulid\Extractor;

$extractor = new Extractor();
$string = "ORDER_01KPKT4PFTKVQ9P1E72F";

echo $extractor->extractPrefix($string), PHP_EOL;
echo $extractor->extractTimestamp($string), PHP_EOL;
echo $extractor->extractRandomString($string), PHP_EOL;

What each extractor method returns

  • extractPrefix() returns the prefix before the underscore, or null
  • extractTimestamp() returns the decoded integer timestamp
  • extractRandomString() returns the random suffix section

Parsing IDs without prefixes

Prefixed and unprefixed ULIDs are both supported:

$plain = "01KPKT4PFTKVQ9P1E72F";
$prefixed = "ORDER_01KPKT4PFTKVQ9P1E72F";

$extractor = new Extractor();

var_dump($extractor->extractPrefix($plain));    // null
var_dump($extractor->extractPrefix($prefixed)); // ORDER

The extractor checks for the underscore separator and adjusts automatically.

Rehydrating before domain validation

One practical pattern is to reconstruct the Ulid as early as possible when an identifier enters the application:

$userId = new Ulid(init: $_GET["id"]);

That keeps parsing logic in one place and lets the rest of the application work with one consistent representation.


If you need to change the shape of the identifier itself, continue with Custom lengths and timestamp sections.