Last active
December 1, 2015 11:15
-
-
Save webeng/2d8801a1bf388f3bfaa4 to your computer and use it in GitHub Desktop.
This script converts an integer to a string using a defined charset. It also converts the string back to an integer. This is useful as a url shortener.
This file contains hidden or 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
// Get the charset to be used, the longer the charset the shortener the output will be | |
function charset($length = 36) { | |
switch ($length) { | |
case '36': | |
$charset = '0123456789abcdefghijklmnopqrstuvwxyz'; | |
break; | |
case '64': | |
$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
break; | |
default: | |
$charset = '0123456789abcdefghijklmnopqrstuvwxyz'; | |
break; | |
} | |
return $charset; | |
} | |
/** | |
* Convert an integer (1337) to a string (3jk) | |
* | |
*/ | |
function int2string( $num, $chars = null ) { | |
if( $chars == null ) | |
$chars = $this->charset(); | |
$string = ''; | |
$len = strlen( $chars ); | |
while( $num >= $len ) { | |
$mod = bcmod( $num, $len ); | |
$num = bcdiv( $num, $len ); | |
$string = $chars[ $mod ] . $string; | |
} | |
$string = $chars[ intval( $num ) ] . $string; | |
return $string; | |
} | |
/** | |
* Convert a string (3jk) to an integer (1337) | |
* | |
*/ | |
function string2int( $string, $chars = null ) { | |
if( $chars == null ) | |
$chars = $this->charset(); | |
$integer = 0; | |
$string = strrev( $string ); | |
$baselen = strlen( $chars ); | |
$inputlen = strlen( $string ); | |
for ($i = 0; $i < $inputlen; $i++) { | |
$index = strpos( $chars, $string[$i] ); | |
$integer = bcadd( $integer, bcmul( $index, bcpow( $baselen, $i ) ) ); | |
} | |
return $integer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment