LewaimaiString.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. //这个文件里面是处理一些常见的字符串相关的函数
  3. //纯工具类,不包含任何业务逻辑
  4. class LewaimaiString {
  5. //产生字母或者数字的随机数
  6. public static function create_noncestr($length = 16)
  7. {
  8. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  9. $str ="";
  10. for ( $i = 0; $i < $length; $i++ ) {
  11. $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  12. }
  13. return $str;
  14. }
  15. //只产生数字的随机数
  16. public static function create_randnum($length = 6)
  17. {
  18. $chars = "0123456789";
  19. $str ="";
  20. for ( $i = 0; $i < $length; $i++ ) {
  21. $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  22. }
  23. return $str;
  24. }
  25. /*
  26. * 生成以20160421这样的数字开头的唯一订单号,可能被猜到,不能用于团购券密码等地方
  27. */
  28. public static function GetUniqueTradeNo($length = 16)
  29. {
  30. if ($length < 16)
  31. {
  32. $length = 16;
  33. }
  34. $string = date('Ymd').substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  35. if ($length > 16)
  36. {
  37. $string .= self::create_randnum($length - 16);
  38. }
  39. return $string;
  40. }
  41. //将前缀和数字id串连起来
  42. //$prefix,前缀,格式如“LWMPT00000000001”
  43. //$id,要拼接的整数
  44. //$length 长度
  45. public static function noToStr($prefix, $id, $length = 16)
  46. {
  47. $id = $id . "";
  48. $idLength = strlen($id);
  49. return substr($prefix,0,$length-$idLength).$id;
  50. }
  51. //对姓名做匿名处理
  52. public static function niming($name)
  53. {
  54. $length = mb_strlen($name, 'utf-8');
  55. if($length == 0 || $length == 1)
  56. {
  57. return '***';
  58. }
  59. else
  60. {
  61. $head = mb_substr($name,0,1,'utf-8');
  62. $last = mb_substr($name,($length-1),1,'utf-8');
  63. }
  64. if ($length == 2)
  65. {
  66. return $head . "***";
  67. }
  68. else
  69. {
  70. return $head . "***" . $last;
  71. }
  72. }
  73. public static function _unserialize($string)
  74. {
  75. return unserialize(preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $string));
  76. }
  77. //用于支付的唯一的订单号,长度24位
  78. public static function GetOutTradeNo()
  79. {
  80. $out_trade_no = "LWM" . strtoupper(uniqid()) . strtoupper(self::create_noncestr(8));
  81. return $out_trade_no;
  82. }
  83. public static function formatMonth($num , $day=0)
  84. {
  85. $year = floor($num/12);
  86. $month = $num%12;
  87. $str = $year ? $year . '年' : '';
  88. $str.= $month ? $month . '个月' : '';
  89. $day > 0 && $str .= $day.'天';
  90. return $str;
  91. }
  92. // 产生店铺的随机字符串
  93. public static function getShopNo()
  94. {
  95. $str = date('Ymd') . self::create_randnum(8);
  96. return $str;
  97. }
  98. }