Home  >  Article  >  Backend Development  >  PHP function to obtain string length under UTF-8 and GBK encoding

PHP function to obtain string length under UTF-8 and GBK encoding

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

  2. * Count string length
  3. *@param $str Counted string
  4. */
  5. function sstrlen($str) {
  6. global $charset;
  7. $n = 0; $p = 0; $c = ”;
  8. $len = strlen($str);
  9. if($charset == 'utf-8′) {
  10. for($i = 0; $i < ; $len; $i++) {
  11. $c = ord($str{$i});
  12. if($c > 252) {
  13. $p = 5;
  14. } elseif($c > 248) {
  15. $p = 4;
  16. } elseif($c > 240) {
  17. $p = 3;
  18. } elseif($c > 224) {
  19. $p = 2;
  20. } elseif($c > 192) {
  21. $p = 1;
  22. } else {
  23. $p = 0;
  24. }
  25. $i+=$p;$n++;
  26. }
  27. } else {
  28. for($i = 0; $i < $len; $ i++) {
  29. $c = ord($str{$i});
  30. if($c > 127) {
  31. $p = 1;
  32. } else {
  33. $p = 0;
  34. }
  35. $i+=$ p;$n++;
  36. }
  37. }

  38. return $n;

  39. }
  40. ?>

Copy code


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