首頁 >後端開發 >php教程 >php中文字串截取 php截取中文字串的程式碼

php中文字串截取 php截取中文字串的程式碼

WBOY
WBOY原創
2016-07-25 09:04:16890瀏覽
  1. /**

  2. @截取中文字符串 适用于GB2312编码
  3. @http://bbs.it-home.org
  4. */
  5. function FSubstr($title,$start,$len="",$magic=true)
  6. {
  7. $length = 0;
  8. if($len == "") $len = strlen($title);

  9. //判断起始为不正确位置

  10. if($start > 0)
  11. {
  12. $cnum = 0;
  13. for($i=0;$i<$start;$i++)
  14. {
  15. if(ord(substr($title,$i,1)) >= 128) $cnum ++;
  16. }
  17. if($cnum%2 != 0) $start--;

  18. unset($cnum);

  19. }

  20. if(strlen($title)<=$len) return substr($title,$start,$len);

  21. $alen = 0;

  22. $blen = 0;

  23. $realnum = 0;

  24. for($i=$start;$i{

  25. $ctype = 0;
  26. $cstep = 0;
  27. $cur = substr($title,$i,1);
  28. if($cur == "&")
  29. {
  30. if(substr($title,$i,4) == "<")
  31. {
  32. $cstep = 4;
  33. $length += 4;
  34. $i += 3;
  35. $realnum ++;
  36. if($magic)
  37. {
  38. $alen ++;
  39. }
  40. }
  41. else if(substr($title,$i,4) == ">")
  42. {
  43. $cstep = 4;
  44. $length += 4;
  45. $i += 3;
  46. $realnum ++;
  47. if($magic)
  48. {
  49. $alen ++;
  50. }
  51. }
  52. else if(substr($title,$i,5) == "&")
  53. {
  54. $cstep = 5;
  55. $length += 5;
  56. $i += 4;
  57. $realnum ++;
  58. if($magic)
  59. {
  60. $alen ++;
  61. }
  62. }
  63. else if(substr($title,$i,6) == """)
  64. {
  65. $cstep = 6;
  66. $length += 6;
  67. $i += 5;
  68. $realnum ++;
  69. if($magic)
  70. {
  71. $alen ++;
  72. }
  73. }
  74. else if(substr($title,$i,6) == "'")
  75. {
  76. $cstep = 6;
  77. $length += 6;
  78. $i += 5;
  79. $realnum ++;
  80. if($magic)
  81. {
  82. $alen ++;
  83. }
  84. }
  85. else if(preg_match("/&#(d+);/i",substr($title,$i,8),$match))
  86. {
  87. $cstep = strlen($match[0]);
  88. $length += strlen($match[0]);
  89. $i += strlen($match[0])-1;
  90. $realnum ++;
  91. if($magic)
  92. {
  93. $blen ++;
  94. $ctype = 1;
  95. }
  96. }
  97. }else{
  98. if(ord($cur)>=128)
  99. {
  100. $cstep = 2;
  101. $length += 2;
  102. $i += 1;
  103. $realnum ++;
  104. if($magic)
  105. {
  106. $blen ++;
  107. $ctype = 1;
  108. }
  109. }else{
  110. $cstep = 1;
  111. $length +=1;
  112. $realnum ++;
  113. if($magic)
  114. {
  115. $alen++;
  116. }
  117. }
  118. }

  119. if($magic)

  120. {
  121. if(($blen*2+$alen) == ($len*2)) break;
  122. if(($blen*2+$alen) == ($len*2+1))
  123. {
  124. if($ctype == 1)
  125. {
  126. $length -= $cstep;
  127. break;
  128. }else{
  129. break;
  130. }
  131. }
  132. }else{
  133. if($realnum == $len) break;
  134. }
  135. }

  136. unset($cur);

  137. unset($alen);
  138. unset($blen);
  139. unset($realnum);
  140. unset($ctype);
  141. unset($cstep);

  142. return substr($title,$start,$length);

  143. }
  144. ?>

复制代码

复制以上代码,在你的php平台中进行测试吧,多动手,水平提高会更快。 程序员之家,您学习路上的好朋友。



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn