When building my URL shortener, ZapX, I ran into a bit of a problem. I wanted to be able to make the shortest possible urls using the characters 0-9, a-z, and A-Z, otherwise known as base 62.
PHP's native base_convert only goes up to base 36, so I was forced to resort to my own devices to get the job done. Long story short, here's one that goes up to base 62:
function extended_base_convert($dec, $base) { $numchart = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $min_base = 2; $max_base = strlen($numchart); if ($base < $min_base || $base > $max_base) return 'N/A'; $value = $dec; $ptr = ceil($value / $base); $buf = array(); do { $buf[$ptr] = substr($numchart, ($value % $base), 1); $value = intval($value / $base); $ptr--; } while ($value > 0); $buf = array_reverse($buf); return implode('', $buf); } |