短网址服务,可能很多朋友都已经不再陌生,现在大部分微博、手机邮件提醒等地方已经有很多应用模式了,并占据了一定的市场。估计很多朋友现在也正在使用。 看过新浪的短连接服务,发现后面主要有6个字符串组成。
太多算法的东西,也没必要去探讨太多,最主要的还是实现,下面是三种方法的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
<?php //纯随机生成方法 function random( $length , $pool = '' ) { $random = '' ; if ( empty ( $pool )) { $pool = 'abcdefghkmnpqrstuvwxyz' ; $pool .= '23456789' ; } srand ((double)microtime()*1000000); for ( $i = 0; $i < $length ; $i ++) { $random .= substr ( $pool ,(rand()%( strlen ( $pool ))), 1); } return $random ; } $a =random(6); print_r( $a ); // 枚举生成方法 function shorturl( $input ) { $base32 = array ( "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" , "l" , "m" , "n" , "o" , "p" , "q" , "r" , "s" , "t" , "u" , "v" , "w" , "x" , "y" , "z" , "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N" , "O" , "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z" ); $hex = md5( $input ); $hexLen = strlen ( $hex ); $subHexLen = $hexLen / 8; $output = array (); for ( $i = 0; $i < $subHexLen ; $i ++) { $subHex = substr ( $hex , $i * 8, 8); $int = 0x3FFFFFFF & (1 * ( '0x' . $subHex )); $out = '' ; for ( $j = 0; $j < 6; $j ++) { $val = 0x0000001F & $int ; $out .= $base32 [ $val ]; $int = $int >> 5; } $output [] = $out ; } return $output ; } $a =shorturl( "http://www.zzvips.com" ); print_r( $a ); //62 位生成方法 function base62( $x ) { $show = '' ; while ( $x > 0) { $s = $x % 62; if ( $s > 35) { $s = chr ( $s +61); } elseif ( $s > 9 && $s <=35) { $s = chr ( $s + 55); } $show .= $s ; $x = floor ( $x /62); } return $show ; } function urlShort( $url ) { $url = crc32( $url ); $result = sprintf( "%u" , $url ); return base62( $result ); } echo urlShort( "http://www.zzvips.com/" ); ?> |