Fun.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace app\common;
  3. class Fun
  4. {
  5. /**
  6. * 通过身份证号返回男1 女2
  7. */
  8. public static function getSexByIdCard($idcard)
  9. {
  10. $sexint = (int)substr($idcard, 16, 1);
  11. return $sexint % 2 === 0 ? 2 : 1;
  12. }
  13. /**
  14. * 通过身份证号返回生日
  15. */
  16. public static function getBirthDayByIdCard($idcard)
  17. {
  18. $birthday = substr($idcard, 6, 4) . '-' . substr($idcard, 10, 2) . '-' . substr($idcard, 12, 2);
  19. return $birthday;
  20. }
  21. /**
  22. * 通过身份证号返回年龄
  23. */
  24. public static function getAgeByIdCard($idcard)
  25. {
  26. $birth = substr($idcard, 6, 4);
  27. $year = date('Y');
  28. return $year - $birth;
  29. }
  30. /**
  31. * 身份证号是否正确
  32. */
  33. public static function isIdCard($idcard)
  34. {
  35. $vCity = [
  36. '11', '12', '13', '14', '15', '21', '22',
  37. '23', '31', '32', '33', '34', '35', '36',
  38. '37', '41', '42', '43', '44', '45', '46',
  39. '50', '51', '52', '53', '54', '61', '62',
  40. '63', '64', '65', '71', '81', '82', '91',
  41. ];
  42. if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $idcard)) return false;
  43. if (!in_array(substr($idcard, 0, 2), $vCity)) return false;
  44. $vStr = preg_replace('/[xX]$/i', 'a', $idcard);
  45. $vLength = strlen($vStr);
  46. if ($vLength == 18) {
  47. $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
  48. } else {
  49. $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
  50. }
  51. if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
  52. if ($vLength == 18) {
  53. $vSum = 0;
  54. for ($i = 17; $i >= 0; $i--) {
  55. $vSubStr = substr($vStr, 17 - $i, 1);
  56. $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
  57. }
  58. if ($vSum % 11 != 1) return false;
  59. }
  60. return true;
  61. }
  62. /**
  63. * 是否手机号
  64. */
  65. public static function isMobile($user_mobile)
  66. {
  67. $chars = "/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/";
  68. if (preg_match($chars, $user_mobile)) {
  69. return true;
  70. } else {
  71. return false;
  72. }
  73. }
  74. /**
  75. * 根据生日获取年龄
  76. */
  77. public static function getAgeByBirth($birthday)
  78. {
  79. if (empty($birthday)) {
  80. return '未知';
  81. }
  82. //格式化出生时间年月日
  83. $byear = date('Y', $birthday);
  84. $bmonth = date('m', $birthday);
  85. $bday = date('d', $birthday);
  86. //格式化当前时间年月日
  87. $tyear = date('Y');
  88. $tmonth = date('m');
  89. $tday = date('d');
  90. //开始计算年龄
  91. $age = $tyear - $byear;
  92. if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
  93. $age--;
  94. }
  95. return $age;
  96. }
  97. }