Skip to content

Instantly share code, notes, and snippets.

@kevinkl3
Last active March 27, 2016 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinkl3/14b1ba9465cb13d13d00 to your computer and use it in GitHub Desktop.
Save kevinkl3/14b1ba9465cb13d13d00 to your computer and use it in GitHub Desktop.
PHP implementation based on this SO answer: http://stackoverflow.com/a/742047/3393666
<?php
class UrlShortener{
private static $alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static function encode($i){
$alphabet = static::$alphabet;
$base = strlen($alphabet);
$result = "";
do{
$result = $alphabet[ $i % $base] . $result;
//$i = intdiv($i, $base); //intdiv requires PHP >= 7
$i = ($i - ($i % $base)) / $base;
}while($i > 0);
return $result;
}
public static function decode($s){
$alphabet = static::$alphabet;
$base = strlen($alphabet);
$id = 0;
$li = strlen($s)-1;
$chars = str_split($s);
foreach($chars as $c){
$v = strpos($alphabet,$c);
$id += $v * pow($base,$li--);
}
return $id;
}
public static function test(){
for($i = 0; $i < 100000; $i++){
$encoded = static::encode($i);
$decoded = static::decode($encoded);
if( $i != $decoded){
echo "Error, $decoded != $i \n";
exit(1);
}else{
echo "Good, $i ($encoded) == $decoded\n";
}
}
}
}
UrlShortener::test();
//To test on command line:
//php UrlShortener.php
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment