create a url friendly short id of a mongo id in php

To create a url-friendly short id from a MongoDB ObjectId, you can use the following function in PHP:

main.php
function objectIdToShortId($objectId) {
    $alphabet = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
    $shortId = '';
    $objectId = str_replace(array('-', '_', '/'), '', $objectId); // remove special characters

    for ($i = 0; $i < 10; $i++) {
        $num = hexdec(substr($objectId, $i * 4, 4)); // get 4 characters at a time
        $shortId .= substr($alphabet, $num % 52, 1); // get character from alphabet based on remainder
    }
    return $shortId;
}
473 chars
12 lines

This function converts the ObjectId to a 10-character string using an alphabet of 52 characters (excluding vowels and similar characters that can be mistaken for one another).

Here's an example of how to use this function:

main.php
$mongoId = new MongoDB\BSON\ObjectId('602f9557ca666c861b2dacf2');
$shortId = objectIdToShortId($mongoId);
echo $shortId; // outputs "PcBdfcjrbp"
145 chars
4 lines

Note that this function will only work with MongoDB ObjectIds, and not with other types of IDs.

gistlibby LogSnag