php截取一定长度的字符串

  1. function ssubstr($string, $length, $dot = ' ...') {
  2. global $charset;
  3. if(strlen($string) <= $length) {
  4. return $string;
  5. }
  6. $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
  7. $strcut = '';
  8. if(strtolower($charset) == 'utf-8') {
  9. $n = $tn = $noc = 0;
  10. while($n < strlen($string)) {
  11. $t = ord($string[$n]);
  12. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  13. $tn = 1; $n++; $noc++;
  14. } elseif (194 <= $t && $t <= 223) {
  15. $tn = 2; $n += 2; $noc += 2;
  16. } elseif (224 <= $t && $t < 239) {
  17. $tn = 3; $n += 3; $noc += 2;
  18. } elseif (240 <= $t && $t <= 247) {
  19. $tn = 4; $n += 4; $noc += 2;
  20. } elseif (248 <= $t && $t <= 251) {
  21. $tn = 5; $n += 5; $noc += 2;
  22. } elseif ($t == 252 || $t == 253) {
  23. $tn = 6; $n += 6; $noc += 2;
  24. } else {
  25. $n++;
  26. }
  27. if($noc >= $length)
  28. {
  29. break;
  30. }
  31. }
  32. if($noc > $length)
  33. {
  34. $n -= $tn;
  35. }
  36. $strcut = substr($string, 0, $n);
  37. } else {
  38. for($i = 0; $i < $length; $i++)
  39. {
  40. $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  41. }
  42. }
  43. $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
  44. return $strcut.$dot;
  45. }
  46. 截取一定长度的字符串(该函数对gb2312使用有效)
  47. <?
  48. function wordscut($string, $length ,$sss=0) {
  49. if(strlen($string) > $length) {
  50. if($sss){
  51. $length=$length - 3;
  52. $addstr=@# ...@#;
  53. }
  54. for($i = 0; $i < $length; $i++) {
  55. if(ord($string[$i]) > 127) {
  56. $wordscut .= $string[$i].$string[$i + 1]; //
  57. $i++; //开源软件:phpfensi.com
  58. } else {
  59. $wordscut .= $string[$i];
  60. }
  61. }
  62. return $wordscut.$addstr;
  63. }
  64. return $string;
  65. }
  66. ?>