Created
April 11, 2012 15:14
-
-
Save bertrandom/2359945 to your computer and use it in GitHub Desktop.
InstagramShortUrl encoding/decoding service
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 | |
namespace Smittn\InstagramBundle\Services; | |
class InstagramShortUrl { | |
private $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; | |
public function __construct() { | |
} | |
function encode($num) { | |
$base_count = strlen($this->alphabet); | |
$encoded = ''; | |
while ($num >= $base_count) { | |
$div = $num/$base_count; | |
$mod = ($num-($base_count*intval($div))); | |
$encoded = $this->alphabet[$mod] . $encoded; | |
$num = intval($div); | |
} | |
if ($num) { | |
$encoded = $this->alphabet[$num] . $encoded; | |
} | |
return $encoded; | |
} | |
function decode($num) { | |
$decoded = 0; | |
$multi = 1; | |
while (strlen($num) > 0) { | |
$digit = $num[strlen($num)-1]; | |
$decoded += $multi * strpos($this->alphabet, $digit); | |
$multi = $multi * strlen($this->alphabet); | |
$num = substr($num, 0, -1); | |
} | |
return $decoded; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment