Heim >Backend-Entwicklung >PHP-Tutorial >截图多余字符,中英文,避免截取中文乱码

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

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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:我小站发现的后台上传程序 Nächster Artikel:数据库字典生成