Home > Backend Development > PHP Tutorial > String interception

String interception

WBOY
Release: 2016-07-25 09:08:35
Original
897 people have browsed it
来自PHPCMS
  1. /**
  2. * 字符截取 支持UTF8/GBK
  3. * @param $string
  4. * @param $length
  5. * @param $dot
  6. */
  7. function str_cut($string, $length, $dot = '...') {
  8. $strlen = strlen($string);
  9. if($strlen <= $length) return $string;
  10. $string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
  11. $strcut = '';
  12. if(strtolower(CHARSET) == 'utf-8') {
  13. $length = intval($length-strlen($dot)-$length/3);
  14. $n = $tn = $noc = 0;
  15. while($n < strlen($string)) {
  16. $t = ord($string[$n]);
  17. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  18. $tn = 1; $n++; $noc++;
  19. } elseif(194 <= $t && $t <= 223) {
  20. $tn = 2; $n += 2; $noc += 2;
  21. } elseif(224 <= $t && $t <= 239) {
  22. $tn = 3; $n += 3; $noc += 2;
  23. } elseif(240 <= $t && $t <= 247) {
  24. $tn = 4; $n += 4; $noc += 2;
  25. } elseif(248 <= $t && $t <= 251) {
  26. $tn = 5; $n += 5; $noc += 2;
  27. } elseif($t == 252 || $t == 253) {
  28. $tn = 6; $n += 6; $noc += 2;
  29. } else {
  30. $n++;
  31. }
  32. if($noc >= $length) {
  33. break;
  34. }
  35. }
  36. if($noc > $length) {
  37. $n -= $tn;
  38. }
  39. $strcut = substr($string, 0, $n);
  40. $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);
  41. } else {
  42. $dotlen = strlen($dot);
  43. $maxi = $length - $dotlen - 1;
  44. $current_str = '';
  45. $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
  46. $replace_arr = array('&',' ', '"', ''', '“', '”', '—', '<', '>', '·', '…',' ');
  47. $search_flip = array_flip($search_arr);
  48. for ($i = 0; $i < $maxi; $i++) {
  49. $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  50. if (in_array($current_str, $search_arr)) {
  51. $key = $search_flip[$current_str];
  52. $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
  53. }
  54. $strcut .= $current_str;
  55. }
  56. }
  57. return $strcut.$dot;
  58. }
复制代码


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template