当前位置:Gxlcms > PHP教程 > php中英文混合字符串的截取函数

php中英文混合字符串的截取函数

时间:2021-07-01 10:21:17 帮助过:22人阅读

  1. /**

  2. * 截取中英文混合的字符串
  3. * by bbs.it-home.org
  4. */
  5. function mb_str_split($string){
  6. # Split at all position not after the start: ^
  7. # and not before the end: $
  8. //$string = iconv('gb2312', 'utf-8//ignore', $string);
  9. return preg_split('/(?}

  10. $string = 'q345e q345d q345c,q345d圆钢,q345e圆钢nm360a耐磨板,欧标s355低合金板 bs700mc汽车板,汽车qste460tm结构钢,船板ah36/eh36/dh36,美标容器板 耐候钢 弹簧钢';

  11. //$charlist = mb_str_split($string);
  12. echo mb_chunk_split($string, 30, '..', true);
  13. echo '
    ';
  14. echo mb_chunk_split($string, 10, '
    ');
  15. function mb_chunk_split($string, $length, $end = '..', $once = false){
  16. //$string = iconv('gb2312', 'utf-8//ignore', $string);
  17. $charlist = mb_str_split($string);
  18. $i = 0;
  19. $j = 0;
  20. $once_array = array();
  21. foreach($charlist as $value){
  22. /* if($once){
  23. if(($i + $j) > $length){
  24. $i--; //尽可能少的
  25. break;
  26. }
  27. }else{
  28. if(($i + $j) >= $length){
  29. $once_array[] = implode('', array_slice($charlist, $once_leng, $i));
  30. $once_leng += $i;
  31. $i = $j = 0;
  32. }
  33. } */
  34. if(($i + $j) >= $length){
  35. if($once)
  36. return implode('', array_slice($charlist, 0, $i-1)) . (count($charlist) <= $i ? '' : $end);
  37. $once_array[] = $i;
  38. $i = $j = 0;
  39. }
  40. if(ord($value) > 127)
  41. $j++; //中文算2个宽度
  42. /*if($value == ',')
  43. $j--;*/
  44. $i++;
  45. }
  46. //末尾补齐
  47. if(array_sum($once_array) < count($charlist))
  48. $once_array[] = $i;
  49. $str_arr = array();
  50. $once_leng = 0;
  51. foreach($once_array as $value){
  52. $str_arr[] = implode('', array_slice($charlist, $once_leng, $value));
  53. $once_leng += $value;
  54. }
  55. return implode($end, $str_arr);
  56. //return implode('', array_slice($charlist, 0, $i)) . (count($charlist) <= $i ? '' : $end);
  57. }
  58. ?>

人气教程排行