note 25715 modified in function.strlen by thiago

From: Date: Wed, 11 Feb 2009 12:17:09 +0000
Subject: note 25715 modified in function.strlen by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150477@lists.php.net to get a copy of this message
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users. <?php function utf8_strlen($str) { $count = 0; for($i = 0; $i < strlen($str); $i++) { $value = ord($str[$i]); if($value > 127) { if($value >= 192 && $value <= 223) $i++; elseif($value >= 224 && $value <= 239) $i = $i + 2; elseif($value >= 240 && $value <= 247) $i = $i + 3; else die('Not a UTF-8 compatible string'); } $count++; } return $count; } ?> --was-- It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I thought I would show off a small function that I made that will tell you the length of a UTF-8 string. This comes in handy if you want to restrict the size of user input to say 30 chars - but don't want to force ascii only input on your users. function utf8_strlen($str) { $count = 0; for($i = 0; $i < strlen($str); $i++) { $value = ord($str[$i]); if($value > 127) { if($value >= 192 && $value <= 223) $i++; elseif($value >= 224 && $value <= 239) $i = $i + 2; elseif($value >= 240 && $value <= 247) $i = $i + 3; else die('Not a UTF-8 compatible string'); } $count++; } return $count; } http://php.net/manual/en/function.strlen.php

« previous php.notes (#150477) next »