一、基类方法:定义字符串、编写转换方法 class NumberHelper { public static $str="abcdefghijklmnopqrstuvwxyz6789ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
/** * Param:将数字转为短字符串 * @param $number * @return string */ public static function generate_code($number) { $out = ""; $codes = self::$str; while ($number > 61) { $m = $number % 62; $out = $codes[$m].$out; $number = ($number - $m) / 62; } return $codes[$number].$out; } /** * Param:将短字符串转为数字 * @param $string * @return float|int */ public static function get_num($string){ $codes = self::$str; $num = 0; for($i=0;$i<strlen($string);$i++){ $n = strlen($string) - $i -1; $pos = strpos($codes,$string[$i]); $num += $pos * pow(62, $n); } return $num; }
}
二、调用转换方法,根据自己定的规则,生成自己需要的短链接
public static function getShotLink($userid,$gid){ //获取用户ID短字符串 $_uid_str = NumberHelper::generate_code($userid); //获取商品ID短字符串 $_good_str = NumberHelper::generate_code($gid]); //拼接生成短链接 $param = '#A='.$_uid_str.'=B='.$_good_str.'#';
return $param
}
三、解析短链接还原参数
public static function getUnShotLink(ShotLink){ //正则匹配解析数据 $ShotLink = self::pregMatchFeng($params['share_data']); $ShotLink = explode('=',str_replace('#','',$ShotLink)); /*解字符串为数字*/ $id = NumberHelper::get_num($ShotLink[1]); $gid = NumberHelper::get_num($ShotLink[3]);
//接着写自己的逻辑
。。。。。。
}
/** * Param: 正则匹配 * @param $data * @return array|mixed */ public static function pregMatchFeng($data){ $_data = []; preg_match_all("/#A=[a-zA-Z]*=B=[a-zA-Z]*#/",$data, $matches); if (!empty($matches[0][0])) { $_data = $matches[0][0]; } return $_data; }