欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php中文字符串截取 php截取中文字符串的代码

程序员文章站 2022-05-13 16:26:05
...
  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{
  14. if(ord(substr($title,$i,1)) >= 128) $cnum ++;
  15. }
  16. if($cnum%2 != 0) $start--;
  17. unset($cnum);

  18. }
  19. if(strlen($title)

  20. $alen = 0;

  21. $blen = 0;
  22. $realnum = 0;

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

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

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

  135. unset($alen);
  136. unset($blen);
  137. unset($realnum);
  138. unset($ctype);
  139. unset($cstep);
  140. return substr($title,$start,$length);

  141. }
  142. ?>
复制代码

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