Skip to content

Instantly share code, notes, and snippets.

@bertrandom
Created April 11, 2012 15:14
Show Gist options
  • Save bertrandom/2359945 to your computer and use it in GitHub Desktop.
Save bertrandom/2359945 to your computer and use it in GitHub Desktop.
InstagramShortUrl encoding/decoding service
<?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