当前位置:Gxlcms > PHP教程 > 截图多余字符,中英文,避免截取中文乱码

截图多余字符,中英文,避免截取中文乱码

时间:2021-07-01 10:21:17 帮助过:31人阅读

截图多余字符,中英文都可以,避免截取中文结尾 ?? 乱码!!
  1. function utf8_strlen($string = null) {
  2. // 将字符串分解为单元
  3. preg_match_all('/./us', $string, $match);
  4. // 返回单元个数
  5. return count($match[0]);
  6. }
  7. function sub_content($content, $length){
  8. $len = utf8_strlen($content);
  9. for($i = 0 ; $i < $len ; $i++){
  10. $arr[$i] = mb_substr($content,$i,1,'utf-8');
  11. }
  12. $get_length = 0;
  13. $result = '';
  14. foreach($arr as $code){
  15. $result .= $code;
  16. if(strlen($code) > 1){
  17. $get_length += 2;
  18. }else{
  19. $get_length += 1;
  20. }
  21. if($get_length >= $length){
  22. break;
  23. }
  24. }
  25. return $result;
  26. }
  27. echo sub_content($rows["Description"],18);
  28. /**
  29. * 字符串截取,支持中文和其他编码
  30. * @param string $str
  31. * @param int $start
  32. * @param int $length
  33. * @param string $charset
  34. * @param boolean $suffix
  35. * @return string
  36. */
  37. function w_substr($str, $start = 0, $length, $charset = "utf-8", $suffix = TRUE) {
  38. $suffix_str = $suffix ? '…' : '';
  39. if(function_exists('mb_substr')) {
  40. return mb_substr($str, $start, $length, $charset) . $suffix_str;
  41. } elseif(function_exists('iconv_substr')) {
  42. return iconv_substr($str, $start, $length, $charset) . $suffix_str;
  43. } else {
  44. $pattern = array();
  45. $pattern['utf-8'] = '/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/';
  46. $pattern['gb2312'] = '/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/';
  47. $pattern['gbk'] = '/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/';
  48. $pattern['big5'] = '/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/';
  49. preg_match_all($pattern[$charset], $str, $matches);
  50. $slice = implode("", array_slice($matches[0], $start, $length));
  51. return $slice . $suffix_str;
  52. }
  53. }

人气教程排行