Created
May 10, 2018 03:22
-
-
Save zhangv/4ffb232ccec7614539db56d4795b8630 to your computer and use it in GitHub Desktop.
UrlShortener
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 UrlShortener{ | |
private static $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';//the real base should not be easy to guess | |
private static $len = 5; | |
private $salt = 0; //simple salt strategy - just shift the base | |
public function __construct($salt = 0){ | |
$this->salt = $salt; | |
} | |
public function base(){ | |
$a = str_split(self::$base); | |
$b = array_slice($a,0,$this->salt); | |
array_splice($a,0,$this->salt); | |
return array_merge($a,$b); | |
} | |
public function encode($num) { | |
$ar = $this->base(); | |
$r = []; | |
$size = count($ar); | |
while($num > 0){ | |
$r[] = $ar[(int)($num % $size) ]; | |
$num = (int) ($num / $size); | |
} | |
return str_pad(implode('',array_reverse($r)),self::$len,$ar[0],STR_PAD_LEFT); | |
} | |
public function decode($str) { | |
$basearr = $this->base(); | |
$baselen = count($basearr); | |
$ar = str_split($str); | |
$size = count($ar); | |
$r = 0; | |
for($i = 0;$i<$size;$i++){ | |
$r = $r*$baselen + array_search($ar[$i],$basearr); | |
} | |
return $r; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment