Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created November 24, 2010 15:20
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 cristobal/713798 to your computer and use it in GitHub Desktop.
Save cristobal/713798 to your computer and use it in GitHub Desktop.
URLHash php
<?php
// Port of http://code.google.com/p/loolu/source/browse/trunk/common/lib/url/hash.py to PHP
/**
* LooLu is Copyright (c) 2009 Shannon Johnson, http://loo.lu/
*/
class URLHash {
private $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private $base = 62;
public function __construct($codeset = null) {
if ($codeset) {
$this->codeset = $codeset;
$this->base = strlen($codeset);
}
}
public function encode($id) {
$hash = "";
while ($id > 0) {
$hash = $this->codeset[$id % $this->base] . $hash;
$id = floor($id / $this->base);
}
return $hash;
}
public function decode($value) {
$id = 0;
$chars = array_reverse(preg_split('//', $value, -1, PREG_SPLIT_NO_EMPTY));
foreach ($chars as $index => $char) {
$n = strpos($this->codeset, $char);
if ($n == -1) {
return 0;
}
$id += $n * pow($this->base, $index);
}
return $id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment