Home  >  Article  >  Backend Development  >  PHP base62编码解码实现

PHP base62编码解码实现

WBOY
WBOYOriginal
2016-06-23 13:40:101585browse

 1 <?php 2 /** 3 *    @desc base62编码解码实现 4 *    @param String $data 5 *    @author Space 6 *    @date 2014/8/6 7 **/ 8  9 function base62_encode($data){10     $base62str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';11     $data = strval($data);12     $base62 = str_split($base62str);13     $len = strlen($data);14     $i = 0;15     $tmpArr = array();16     while($i<$len){17         $val = $data[$i];18         $tmp = str_pad(decbin(ord($data[$i])),8,'0',STR_PAD_LEFT );19         $temp = str_split($tmp,4);20         $tmpArr = array_merge($tmpArr,$temp);21         ++$i;22     }23     $result = '';24     $i = 0;25     foreach($tmpArr as $arr){26         $temp = bindec($arr)*4+$i%2;27         $result .= $base62[$temp];28         ++$i;29     }30     return $result;31 }32 33 function base62_decode($data){34     $base62str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';35     $data = strval($data);36     $base62 = str_split($base62str);37     $base62Arr = array_flip($base62);38     if(!preg_match('/[a-zA-Z0-9]+/',$data)){39         return false;40     }41     $len = strlen($data);42     $i = 0;43     $tempArr = array();44     while($i<$len){45         $temp = decbin(($base62Arr[$data[$i]]-$i%2)/4);46         $tempArr[] = str_pad($temp,4,'0',STR_PAD_LEFT);47         ++$i;48     }49     $result = '';50     $tempArr = array_chunk($tempArr,2);51     foreach($tempArr as $arr){52         $result .= chr(bindec(join('',$arr)));53     }54     return $result;55 }

还可以根据需要$base62str变量中字符随机排序下,相当于一个简易的加密,不过意义不大。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn