php字符串截取函数,支持中文 utf-8截取

  1. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  5. <title>environment</title>
  6. </head>
  7. <?php
  8. $str = "中12hb千钧一发lap";
  9. echo mb_substr($str,0,5,'utf-8');echo '<br>';
  10. echo mb_substr($str,5,3,'utf-8');echo '<br>';
  11. echo mb_substr($str,8,4,'utf-8');
  12. ?>
  13. <body>
  14. </body>
  15. </html>
  16. <?php
  17. function str_wrap1($str,$elen=30)
  18. {
  19. $tlen = mb_strlen($str,"utf8"); //共有多少字
  20. //$elen = 8; //每行字符串长度8个字符、4个汉字
  21. $dlen = 0; //每行显示长度
  22. $str_wrap = '';
  23. for($i=0;$i<$tlen;$i++)
  24. {
  25. $tmpchar = mb_substr($str,$i,1,"utf8");
  26. if(strlen($tmpchar) == 3)
  27. $charlen = 2;
  28. else
  29. $charlen = 1;
  30. if( $dlen < $elen-1 )
  31. {
  32. $dlen += $charlen;
  33. $str_wrap .= $tmpchar;
  34. }//开源软件:phpfensi.com
  35. else
  36. {
  37. $str_wrap .= "<br>".$tmpchar;
  38. $dlen = $charlen;
  39. }
  40. }
  41. return $str_wrap;
  42. }
  43. echo str_wrap1($str,5);
  44. ?>