php创建短ID Create short IDs with PHP - Like Youtube or TinyURL
?
?
The alphabet has 26 characters. That's a lot more than 10 digits. If we also distinguish upper- and lowercase, and add digits to the bunch or the heck of it, we already have (26 x 2 + 10)?62 options?we can use?per position?in the ID.
Now of course we can also add additional funny characters to 'the bunch' like - / * & # but those may cause problems in URLs and that's our target audience for now.
OK so because there are roughly?6x more characters?we will use per position, IDs will get much?shorter. We can just fit a lot?more data in each position.
This is basically what url shortening services do like tinyurl, is.gd, or bit.ly. But similar IDs can also be found at youtube:?http://www.youtube.com/watch?v=yzNjIBEdyww
Now unlike Database servers: webservers are easy to scale so you can let them do a bit of converting to ease the life of your users, while keeping your database fast with numbers (MySQL really likes them plain numbers ; ).
To do the conversion I've written a PHP function that can translate big numbers to short strings and vice versa. I call it: alphaID.
The resulting string is not hard to decipher, but it can be a very nice feature to make URLs or directorie structures more compact and significant.
So basically:
?
?
?
Example
Running:
/** * HaXe version of AlphabeticID * Author: Andy Li <andy@onthewings.net> * ported from... * * Javascript AlphabeticID class * Author: Even Simon <even.simon@gmail.com> * which is based on a script by Kevin van Zonneveld <kevin@vanzonneveld.net>) * * Description: Translates a numeric identifier into a short string and backwords. * http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/ **/ class AlphaID { static public var index:String = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; static public function encode(_number:Int):String { var strBuf = new StringBuf(); var i = 0; var end = Math.floor(Math.log(_number)/Math.log(index.length)); while(i <= end) { strBuf.add(index.charAt((Math.floor(_number / bcpow(index.length, i++)) % index.length))); } return strBuf.toString(); } static public function decode(_string:String):Int { var str = reverseString(_string); var ret = 0; var i = 0; var end = str.length - 1; while(i <= end) { ret += Std.int(index.indexOf(str.charAt(i)) * (bcpow(index.length, end-i))); ++i; } return ret; } inline static private function bcpow(_a:Float, _b:Float):Float { return Math.floor(Math.pow(_a, _b)); } inline static private function reverseString(inStr:String):String { var ary = inStr.split(""); ary.reverse(); return ary.join(""); }}?
?来源:http://kevin.vanzonneveld.net/techblog/article/create_short_ids_with_php_like_youtube_or_tinyurl/
?
?