Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created November 4, 2011 20:12
Show Gist options
  • Save xeoncross/1340365 to your computer and use it in GitHub Desktop.
Save xeoncross/1340365 to your computer and use it in GitHub Desktop.
URL shortener
<?php
class Bijective
{
public $dictionary = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public function __construct()
{
$this->dictionary = str_split($this->dictionary);
}
function encode($i)
{
if ($i == 0)
return $this->dictionary[0];
$result = '';
$base = count($this->dictionary);
while ($i > 0)
{
$result[] = $this->dictionary[($i % $base)];
$i = floor($i / $base);
}
$result = array_reverse($result);
return join("", $result);
}
function decode($input)
{
$i = 0;
$base = count($this->dictionary);
$input = str_split($input);
foreach($input as $char)
{
$pos = array_search($char, $this->dictionary);
$i = $i * $base + $pos;
}
return $i;
}
}
// Sample usage
$Bijective = new Bijective();
header('Content-Type: text/plain');
print $Bijective->encode(123654). "\n\n";
print $Bijective->decode($Bijective->encode(123654)). "\n\n";
@alganet
Copy link

alganet commented Nov 4, 2011

If you don't worry about a custom dictionary (most people don't), the native base_convert() functiona is the way to go:

<?php

$fromBase = 10;
$toBase = 36;
print base_convert(123654, $fromBase, $toBase);

@xeoncross
Copy link
Author

@alganet, actually it's even better than that using the GMP extension: gmp_strval(gmp_init($number, 10), 62);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment