You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

39 lines
1.2 KiB

  1. <?php
  2. namespace Kuxin\Helper;
  3. use Kuxin\Config;
  4. /**
  5. * Class Str
  6. *
  7. * @package Kuxin\Helper
  8. * @author Pakey <pakey@qq.com>
  9. */
  10. class Str
  11. {
  12. /**
  13. * 字符串截取,支持中文和其他编码
  14. *
  15. * @param string $string 需要转换的字符串
  16. * @param string $length 截取长度
  17. * @param string $suffix 截断显示字符
  18. * @param int $start 开始位置
  19. * @return string
  20. */
  21. public static function truncate($string, $length, $suffix = '', $start = 0)
  22. {
  23. if (empty($string) or empty($length) or strlen($string) < $length)
  24. return $string;
  25. if (function_exists('mb_substr')) {
  26. $slice = mb_substr($string, $start, $length, Config::get('template.output_charset') == 'gbk' ? 'gbk' : 'utf-8');
  27. } elseif (function_exists('iconv_substr')) {
  28. $slice = iconv_substr($string, $start, $length, Config::get('template.output_charset') == 'gbk' ? 'gbk' : 'utf-8');
  29. } else {
  30. preg_match_all('/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/', $string, $match);
  31. $slice = implode('', array_slice(reset($match), $start, $length));
  32. }
  33. return $slice . $suffix;
  34. }
  35. }