截圖多餘字元,中英文,避免截取中文亂碼

來源:互聯網
上載者:User
多餘字元,中英文都可以,避免截取中文結尾 ?? 亂碼!!
  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. }
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.