Home  >  Article  >  Backend Development  >  Function to get the length of a UTF8 encoded string

Function to get the length of a UTF8 encoded string

WBOY
WBOYOriginal
2016-07-25 09:07:14980browse
  1. /*
  2. * Program for UTF8 encoding
  3. * Get the length of the string, one Chinese represents 3 lengths
  4. */
  5. function utf8_strlen($str) {
  6. $count = 0 ;
  7. for($i = 0; $i < strlen($str); $i++){
  8. $value = ord($str[$i]);
  9. if($value > 127) {
  10. $count++ ;
  11. if($value >= 192 && $value <= 223) $i++;
  12. elseif($value >= 224 && $value <= 239) $i = $i + 2;
  13. elseif($ value >= 240 && $value <= 247) $i = $i + 3;
  14. else die('Not a UTF-8 compatible string');
  15. }
  16. $count++;
  17. }
  18. return $count;
  19. }
  20. ?>
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