Home >Backend Development >PHP Tutorial >PHP function to intercept Chinese characters (utf-8 format)

PHP function to intercept Chinese characters (utf-8 format)

WBOY
WBOYOriginal
2016-07-25 09:04:17928browse
  1. /**

  2. @UTF-8 Chinese character truncation program
  3. @http://bbs.it-home.org
  4. */
  5. $str = "321 This is a test string";
  6. $str1 = "()()";
  7. echo subUTF8str ($str,0,3)."
    ";
  8. echo subUTF8str($str,0,4)."
    ";
  9. echo subUTF8str($str1,0,4)."< br>";
  10. echo subUTF8str($str1,0,10)."
    ";

  11. function subUTF8str($str,$start=0,$length=80){

  12. $cur_len = 0; //The string length understood by humans
  13. $all_len = strlen($str); //The string length understood by machines
  14. if($length > $all_len)
  15. {
  16. return $str;
  17. }
  18. for($i = 0;$i < $all_len;)
  19. {
  20. if($cur_len == $start)
  21. {
  22. break;
  23. }
  24. if (ord($str[$i]) > 127 )
  25. {
  26. $i += 3;
  27. }else{
  28. $i += 1;
  29. }
  30. $cur_len ++;
  31. }
  32. $start_pos = $i;
  33. $temp_pos = $cur_len;
  34. for(;$ cur_len - $temp_pos < $length;)
  35. {
  36. if($i >= $all_len)
  37. break;
  38. if (ord($str[$i]) > 127)
  39. {
  40. $i += 3 ;
  41. }else{
  42. $i += 1;
  43. }
  44. $cur_len ++;
  45. }
  46. $end_pos = $i;
  47. return substr($str,$start_pos,$end_pos);
  48. }
  49. ?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn