StringHelper.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. namespace common\helpers;
  3. use Yii;
  4. use yii\helpers\BaseStringHelper;
  5. use Ramsey\Uuid\Uuid;
  6. /**
  7. * Class StringHelper
  8. * @package common\helpers
  9. * @author qimall
  10. */
  11. class StringHelper extends BaseStringHelper
  12. {
  13. /**
  14. * 生成Uuid
  15. *
  16. * @param string $type 类型 默认时间 time/md5/random/sha1/uniqid 其中uniqid不需要特别开启php函数
  17. * @param string $name 加密名
  18. * @return string
  19. * @throws \Exception
  20. */
  21. public static function uuid($type = 'uniqid', $name = 'php.net')
  22. {
  23. switch ($type) {
  24. // php自带的唯一id
  25. case 'uniqid' :
  26. return md5(uniqid(md5(microtime(true) . self::random(8)), true));
  27. break;
  28. }
  29. return '';
  30. }
  31. /**
  32. * 日期转时间戳
  33. *
  34. * @param $value
  35. * @return false|int
  36. */
  37. public static function dateToInt($value)
  38. {
  39. if (empty($value)) {
  40. return $value;
  41. }
  42. if (!is_numeric($value)) {
  43. return strtotime($value);
  44. }
  45. return $value;
  46. }
  47. /**
  48. * 时间戳转日期
  49. *
  50. * @param $value
  51. * @return false|int
  52. */
  53. public static function intToDate($value, $format = 'Y-m-d H:i:s')
  54. {
  55. if (empty($value)) {
  56. return date($format);
  57. }
  58. if (is_numeric($value)) {
  59. return date($format, $value);
  60. }
  61. return $value;
  62. }
  63. /**
  64. * 获取缩略图地址
  65. *
  66. * @param string $url
  67. * @param int $width
  68. * @param int $height
  69. */
  70. public static function getThumbUrl($url, $width, $height)
  71. {
  72. $url = str_replace('attachment/images', 'attachment/thumb', $url);
  73. return self::createThumbUrl($url, $width, $height);
  74. }
  75. /**
  76. * 创建缩略图地址
  77. *
  78. * @param string $url
  79. * @param int $width
  80. * @param int $height
  81. */
  82. public static function createThumbUrl($url, $width, $height)
  83. {
  84. $url = explode('/', $url);
  85. $nameArr = explode('.', end($url));
  86. $url[count($url) - 1] = $nameArr[0] . "@{$width}x{$height}." . $nameArr[1];
  87. return implode('/', $url);
  88. }
  89. /**
  90. * 获取压缩图片地址
  91. *
  92. * @param $url
  93. * @param $quality
  94. * @return string
  95. */
  96. public static function getAliasUrl($url, $alias = 'compress')
  97. {
  98. $url = explode('/', $url);
  99. $nameArr = explode('.', end($url));
  100. $url[count($url) - 1] = $nameArr[0] . "@{$alias}." . $nameArr[1];
  101. return implode('/', $url);
  102. }
  103. /**
  104. * 根据Url获取本地绝对路径
  105. *
  106. * @param $url
  107. * @param string $type
  108. * @return string
  109. */
  110. public static function getLocalFilePath($url, $type = 'images')
  111. {
  112. if (RegularHelper::verify('url', $url)) {
  113. if (!RegularHelper::verify('url', Yii::getAlias("@attachurl"))) {
  114. $hostInfo = Yii::$app->request->hostInfo . Yii::getAlias("@attachurl");
  115. $url = str_replace($hostInfo, '', $url);
  116. } else {
  117. $url = str_replace(Yii::getAlias("@attachurl"), '', $url);
  118. }
  119. } else {
  120. $url = str_replace(Yii::getAlias("@attachurl"), '', $url);
  121. }
  122. return Yii::getAlias("@attachment") . $url;
  123. }
  124. /**
  125. * 分析枚举类型配置值
  126. *
  127. * 格式 a:名称1,b:名称2
  128. *
  129. * @param $string
  130. * @return array
  131. */
  132. public static function parseAttr($string)
  133. {
  134. $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
  135. if (strpos($string, ':')) {
  136. $value = [];
  137. foreach ($array as $val) {
  138. list($k, $v) = explode(':', $val);
  139. $value[$k] = $v;
  140. }
  141. } else {
  142. $value = $array;
  143. }
  144. return $value;
  145. }
  146. /**
  147. * 返回字符串在另一个字符串中第一次出现的位置
  148. *
  149. * @param $string
  150. * @param $find
  151. * @return bool
  152. * true | false
  153. */
  154. public static function strExists($string, $find)
  155. {
  156. return !(strpos($string, $find) === false);
  157. }
  158. /**
  159. * XML 字符串载入对象中
  160. *
  161. * @param string $string 必需。规定要使用的 XML 字符串
  162. * @param string $class_name 可选。规定新对象的 class
  163. * @param int $options 可选。规定附加的 Libxml 参数
  164. * @param string $ns
  165. * @param bool $is_prefix
  166. * @return bool|\SimpleXMLElement
  167. */
  168. public static function simplexmlLoadString(
  169. $string,
  170. $class_name = 'SimpleXMLElement',
  171. $options = 0,
  172. $ns = '',
  173. $is_prefix = false
  174. )
  175. {
  176. libxml_disable_entity_loader(true);
  177. if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
  178. return false;
  179. }
  180. return simplexml_load_string($string, $class_name, $options, $ns, $is_prefix);
  181. }
  182. /**
  183. * 字符串提取汉字
  184. *
  185. * @param $string
  186. * @return mixed
  187. */
  188. public static function strToChineseCharacters($string)
  189. {
  190. preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $string, $chinese);
  191. return $chinese;
  192. }
  193. /**
  194. * 字符首字母转大小写
  195. *
  196. * @param $str
  197. * @return mixed
  198. */
  199. public static function strUcwords($str)
  200. {
  201. return str_replace(' ', '', ucwords(str_replace('-', ' ', $str)));
  202. }
  203. /**
  204. * 下划线转驼峰命名法风格
  205. *
  206. * @param $str
  207. * @param $separator // 被替换的字符
  208. * @param $ucfirst // 首字母是否大写
  209. * @return string
  210. */
  211. public static function camelize($str, $separator = '_', $ucfirst = false)
  212. {
  213. $str = str_replace($separator, " ", strtolower($str));
  214. $str = ltrim(str_replace(" ", "", ucwords($str)), $separator);
  215. return $ucfirst == true ? ucfirst($str) : lcfirst($str);
  216. }
  217. /**
  218. * 驼峰命名法转下划线风格
  219. *
  220. * @param $str
  221. * @return string
  222. */
  223. public static function toUnderScore($str)
  224. {
  225. $array = [];
  226. for ($i = 0; $i < strlen($str); $i++) {
  227. if ($str[$i] == strtolower($str[$i])) {
  228. $array[] = $str[$i];
  229. } else {
  230. if ($i > 0) {
  231. $array[] = '-';
  232. }
  233. $array[] = strtolower($str[$i]);
  234. }
  235. }
  236. return implode('', $array);
  237. }
  238. /**
  239. * 获取字符串后面的字符串
  240. *
  241. * @param string $fileName 文件名
  242. * @param string $type 字符类型
  243. * @param int $length 长度
  244. * @return bool|string
  245. */
  246. public static function clipping($fileName, $type = '.', $length = 0)
  247. {
  248. return substr(strtolower(strrchr($fileName, $type)), $length);
  249. }
  250. /**
  251. * 获取随机字符串
  252. *
  253. * @param $length
  254. * @param bool $numeric
  255. * @return string
  256. */
  257. public static function random($length, $numeric = false)
  258. {
  259. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  260. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  261. $hash = '';
  262. if (!$numeric) {
  263. $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
  264. $length--;
  265. }
  266. $max = strlen($seed) - 1;
  267. $seed = str_split($seed);
  268. for ($i = 0; $i < $length; $i++) {
  269. $hash .= $seed[mt_rand(0, $max)];
  270. }
  271. return $hash;
  272. }
  273. /**
  274. * 获取数字随机字符串
  275. *
  276. * @param bool $prefix 判断是否需求前缀
  277. * @param int $length 长度
  278. * @return string
  279. */
  280. public static function randomNum($prefix = false, $length = 8)
  281. {
  282. $str = $prefix ?? '';
  283. return $str . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, $length);
  284. }
  285. /**
  286. * 去除内容的注释
  287. *
  288. * @param $content
  289. * @return string|string[]|null
  290. */
  291. public static function removeAnnotation($content)
  292. {
  293. return preg_replace("/(\/\*(\s|.)*?\*\/)|(\/\/.(\s|.*))|(#(\s*)?(.*))/", '',
  294. str_replace(["\r\n", "\r"], "\n", $content));
  295. }
  296. /**
  297. * 生成随机code
  298. *
  299. * @param $merchant_id
  300. * @return false|string
  301. */
  302. public static function code($merchant_id)
  303. {
  304. $time_str = date('YmdHis');
  305. $rand_code = rand(0, 999999);
  306. return substr(md5($time_str . $rand_code . $merchant_id), 16, 32);
  307. }
  308. /**
  309. * 字符串匹配替换
  310. *
  311. * @param string $search 查找的字符串
  312. * @param string $replace 替换的字符串
  313. * @param string $subject 字符串
  314. * @param null $count
  315. * @return mixed
  316. */
  317. public static function replace($search, $replace, $subject, &$count = null)
  318. {
  319. return str_replace($search, $replace, $subject, $count);
  320. }
  321. /**
  322. * 验证是否Windows
  323. *
  324. * @return bool
  325. */
  326. public static function isWindowsOS()
  327. {
  328. return strncmp(PHP_OS, 'WIN', 3) === 0;
  329. }
  330. /**
  331. * 文字自动换行
  332. *
  333. * @param integer $fontsize 字体大小
  334. * @param integer $angle 角度
  335. * @param string $fontface 字体名称
  336. * @param string $string 字符串
  337. * @param integer $width 预设宽度
  338. * @param null $max_line
  339. * @return string
  340. */
  341. public static function autoWrap($font_size, $angle, $font_face, $string, $width, $max_line = null)
  342. {
  343. // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
  344. $content = "";
  345. // 将字符串拆分成一个个单字 保存到数组 letter 中
  346. $letter = [];
  347. for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
  348. $letter[] = mb_substr($string, $i, 1, 'UTF-8');
  349. }
  350. $line_count = 0;
  351. foreach ($letter as $l) {
  352. $test_str = $content . " " . $l;
  353. $test_box = imagettfbbox($font_size, $angle, $font_face, $test_str);
  354. // 判断拼接后的字符串是否超过预设的宽度
  355. if (($test_box[2] > $width) && ($content !== "")) {
  356. $line_count++;
  357. if ($max_line && $line_count >= $max_line) {
  358. $content = mb_substr($content, 0, -1, 'UTF-8') . "...";
  359. break;
  360. }
  361. $content .= "\n";
  362. }
  363. $content .= $l;
  364. }
  365. return $content;
  366. }
  367. /**
  368. * 省略文字
  369. *
  370. * @param $text
  371. * @param int $num
  372. * @return string|string[]
  373. */
  374. public static function textOmit($string, $num = 26)
  375. {
  376. $letter = [];
  377. for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
  378. $letter[] = mb_substr($string, $i, 1, 'UTF-8');
  379. }
  380. $content = "";
  381. foreach ($letter as $key => $l) {
  382. if ($key + 1 == $num) {
  383. $content .= '...';
  384. break;
  385. }
  386. $content .= $l;
  387. }
  388. return $content;
  389. }
  390. /**
  391. * @param $string
  392. * @return string
  393. */
  394. public static function strToInt($string)
  395. {
  396. $versionArr = explode('.', $string);
  397. if (count($versionArr) > 3) {
  398. return false;
  399. }
  400. $version_id = 0;
  401. isset($versionArr[0]) && $version_id += BcHelper::mul((int)$versionArr[0], 100000000000, 12);
  402. isset($versionArr[1]) && $version_id += BcHelper::mul((int)$versionArr[1], 10000000, 8);
  403. isset($versionArr[2]) && $version_id += BcHelper::mul((int)$versionArr[2], 1000, 4);
  404. return $version_id;
  405. }
  406. /**
  407. * 将一个字符串部分字符用*替代隐藏
  408. *
  409. * @param string $string 待转换的字符串
  410. * @param int $bengin 起始位置,从0开始计数,当$type=4时,表示左侧保留长度
  411. * @param int $len 需要转换成*的字符个数,当$type=4时,表示右侧保留长度
  412. * @param int $type 转换类型:0,从左向右隐藏;1,从右向左隐藏;2,从指定字符位置分割前由右向左隐藏;3,从指定字符位置分割后由左向右隐藏;4,保留首末指定字符串
  413. * @param string $glue 分割符
  414. * @return bool|string
  415. */
  416. public static function hideStr($string, $bengin = 0, $len = 4, $type = 0, $glue = "@")
  417. {
  418. if (empty($string)) {
  419. return false;
  420. }
  421. $array = [];
  422. if ($type == 0 || $type == 1 || $type == 4) {
  423. $strlen = $length = mb_strlen($string);
  424. while ($strlen) {
  425. $array[] = mb_substr($string, 0, 1, "utf8");
  426. $string = mb_substr($string, 1, $strlen, "utf8");
  427. $strlen = mb_strlen($string);
  428. }
  429. }
  430. switch ($type) {
  431. case 0 :
  432. for ($i = $bengin; $i < ($bengin + $len); $i++) {
  433. isset($array[$i]) && $array[$i] = "*";
  434. }
  435. $string = implode("", $array);
  436. break;
  437. case 1 :
  438. $array = array_reverse($array);
  439. for ($i = $bengin; $i < ($bengin + $len); $i++) {
  440. isset($array[$i]) && $array[$i] = "*";
  441. }
  442. $string = implode("", array_reverse($array));
  443. break;
  444. case 2 :
  445. $array = explode($glue, $string);
  446. $array[0] = self::hideStr($array[0], $bengin, $len, 1);
  447. $string = implode($glue, $array);
  448. break;
  449. case 3 :
  450. $array = explode($glue, $string);
  451. $array[1] = self::hideStr($array[1], $bengin, $len, 0);
  452. $string = implode($glue, $array);
  453. break;
  454. case 4 :
  455. $left = $bengin;
  456. $right = $len;
  457. $tem = array();
  458. for ($i = 0; $i < ($length - $right); $i++) {
  459. if (isset($array[$i])) {
  460. $tem[] = $i >= $left ? "*" : $array[$i];
  461. }
  462. }
  463. $array = array_chunk(array_reverse($array), $right);
  464. $array = array_reverse($array[0]);
  465. for ($i = 0; $i < $right; $i++) {
  466. $tem[] = $array[$i];
  467. }
  468. $string = implode("", $tem);
  469. break;
  470. }
  471. return $string;
  472. }
  473. /**
  474. * 判断返回数据是否json
  475. * @param $string
  476. * @return bool
  477. */
  478. public static function isJson($string)
  479. {
  480. if (is_array($string) || is_object($string)) {
  481. return false;
  482. }
  483. json_decode($string);
  484. if (json_last_error() == JSON_ERROR_NONE) {
  485. //是否返回数组
  486. $data = json_decode($string, 1);
  487. return is_array($data);
  488. }
  489. return false;
  490. }
  491. public static function generateOrderNo($prefix = ''){
  492. // 优化唯一性保证:使用random_int()代替rand(),并结合微调以生成更唯一的ID
  493. $randInt = random_int(100000, 999999);
  494. // 日期时间戳处理
  495. $dateTimeStr = date('YmdHis');
  496. // 保证前缀不为空字符串且不超过一定长度(例如20个字符)
  497. $prefix = trim($prefix, '0');
  498. if (strlen($prefix) > 20) {
  499. $prefix = substr($prefix, 0, 20);
  500. }
  501. // 生成订单号,保证总长度为17(前缀+日期时间戳+随机数)
  502. $orderNo = $prefix . $dateTimeStr . str_pad($randInt, 6, '0', STR_PAD_LEFT);
  503. return $orderNo;
  504. }
  505. public static function createRandomString($length = 6)
  506. {
  507. if ($length <= 1) return '';
  508. $numberArr = range(1, 9);
  509. $lowercaseArr = range('a', 'z');
  510. $capitalArr = range('A', 'Z');
  511. $arr = array_merge($numberArr, $lowercaseArr, $capitalArr);
  512. shuffle($arr);
  513. $code = '';
  514. $codeArr = [];
  515. $arrLength = count($arr);
  516. for ($i = 0; $i < $length; $i++) {
  517. $rand = mt_rand(0, $arrLength - 1);
  518. $code .= $arr[$rand];
  519. $codeArr[] = $arr[$rand];
  520. }
  521. // 全部都是英文
  522. if (ctype_alpha($code)) {
  523. $replaceCount = rand(1, $length - 1);
  524. shuffle($codeArr);
  525. $codeLength = count($codeArr);
  526. for ($j = 1; $j <= $replaceCount; $j++) {
  527. $codeIndex = mt_rand(0, $codeLength - 1);
  528. shuffle($numberArr);
  529. $numberIndex = array_rand($numberArr);
  530. $codeArr[$codeIndex] = $numberArr[$numberIndex];
  531. }
  532. $code = implode($codeArr);
  533. }
  534. return $code;
  535. }
  536. public static function generateRandCode($length = 6)
  537. {
  538. $sourceString = '1234567890';
  539. $string = str_shuffle($sourceString); //打乱字符串
  540. $code = substr($string, 0, $length); //substr(string,start,length);返回字符串的一部分
  541. return $code;
  542. }
  543. /**
  544. * 通过版本号生产版本号数字
  545. */
  546. public static function getVersionNum($version = '')
  547. {
  548. if (empty($version)) {
  549. return false;
  550. }
  551. $versionArr = explode('.', $version);
  552. if (count($versionArr) > 3) {
  553. return false;
  554. }
  555. $versionNum = 0;
  556. $v1 = sprintf('%03s', (int) $versionArr[0]);
  557. $v2 = sprintf('%03s', (int) $versionArr[1]);
  558. $v3 = sprintf('%03s', (int) $versionArr[2]);
  559. return (int) "{$v1}{$v2}{$v3}";
  560. }
  561. /**
  562. * 生成随机姓名
  563. * @Author:lun
  564. * @Date:2024-07-02 11:14
  565. * @Copyright:copyright(c)2024 广东七件事集团
  566. * @return string
  567. */
  568. public static function randName()
  569. {
  570. $random = rand(1, 10);
  571. $first = ["赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "蒋", "沈", "韩", "杨", "朱", "秦", "许", "何", "吕", "胡", "张", "孔", "曹", "严", "魏", "陶", "姜", "戚", "谢", "邹", "林", "苏", "潘", "葛"];
  572. $last = ["梓", "秋", "胜", "智", "勇", "德", "欣", "意", "涵", "仪", "汐", "语", "颖", "铄", "景", "梦", "苒", "舒", "思", "沁", "如", "辰", "梵", "天", "钊", "恬", "玮", "泉", "静", "泽", "影", "瑞", "衡", "衿", "华", "新", "显", "昕", "柳", "然", "韬", "珊", "俊", "悦", "宜", "嘉", "琪", "惠", "山", "威", "赫", "瑶", "月", "斐", "致", "若"];
  573. if ($random <= 3) {// 两个字姓名跟三个字姓名占比大概按照3/7分
  574. $name = $first[array_rand($first)] . "*";
  575. return $name;
  576. } else {
  577. $name = $first[array_rand($first)] . "*" . $last[array_rand($last)];
  578. return $name;
  579. }
  580. }
  581. public static function getIdCardInfo($id_card)
  582. {
  583. $year = substr($id_card, 6, 4);
  584. $month = substr($id_card, 10, 2);
  585. $day = substr($id_card, 12, 2);
  586. $sex_code = substr($id_card, 16, 1);
  587. if ($sex_code % 2 == 0) {
  588. $sex = '女';
  589. } else {
  590. $sex = '男';
  591. }
  592. return ['birthday' => $year . '-' . $month . '-' . $day, 'sex' => $sex];
  593. }
  594. }