CString.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | A3Mall
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: xzncit <158373108@qq.com>
  8. // +----------------------------------------------------------------------
  9. namespace mall\utils;
  10. class CString {
  11. /**
  12. * 截取UTF-8编码下字符串的函数
  13. * @param string $str 被截取的字符串
  14. * @param int $length 截取的长度
  15. * @param bool $append 是否附加省略号
  16. * @return string
  17. */
  18. public static function msubstr($str, $length = 0, $append = true) {
  19. $str = trim($str);
  20. $strlength = strlen($str);
  21. if ($length == 0 || $length >= $strlength) {
  22. return $str;
  23. } elseif ($length < 0) {
  24. $length = $strlength + $length;
  25. if ($length < 0) {
  26. $length = $strlength;
  27. }
  28. }
  29. if (function_exists('mb_substr')) {
  30. $newstr = mb_substr($str, 0, $length);
  31. } elseif (function_exists('iconv_substr')) {
  32. $newstr = iconv_substr($str, 0, $length);
  33. } else {
  34. $newstr = substr($str, 0, $length);
  35. }
  36. if ($append && $str != $newstr) {
  37. $newstr .= '...';
  38. }
  39. return self::removeEmojiChar($newstr);
  40. }
  41. /*
  42. * 删除多余空白字符
  43. */
  44. public static function removeEmpty($str) {
  45. $string = str_replace(["&nbsp;", " "], [' ', ' '], $str);
  46. return trim(preg_replace("/[\r\n\t ]{1,}/", '', $string));
  47. }
  48. public static function removeEmojiChar($str){
  49. $mbLen = mb_strlen($str);
  50. $strArr = [];
  51. for ($i = 0; $i < $mbLen; $i++) {
  52. $mbSubstr = mb_substr($str, $i, 1, 'utf-8');
  53. if (strlen($mbSubstr) >= 4) {
  54. continue;
  55. }
  56. $strArr[] = $mbSubstr;
  57. }
  58. return implode('', $strArr);
  59. }
  60. }