Created
November 4, 2011 20:12
-
-
Save xeoncross/1340365 to your computer and use it in GitHub Desktop.
URL shortener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, 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
If you don't worry about a custom dictionary (most people don't), the native base_convert() functiona is the way to go: