note 95289 modified in function.mb-check-encoding by danbrown

From: Date: Thu, 24 Dec 2009 20:14:57 +0000
Subject: note 95289 modified in function.mb-check-encoding by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-164311@lists.php.net to get a copy of this message
In order to check if a string is encoded correctly in utf-8, I suggest the following function, that implements the RFC3629 better than mb_check_encoding(): <?php function check_utf8($str) { $len = strlen($str); for($i = 0; $i < $len; $i++){ $c = ord($str[$i]); if ($c > 128) { if (($c > 247)) return false; elseif ($c > 239) $bytes = 4; elseif ($c > 223) $bytes = 3; elseif ($c > 191) $bytes = 2; else return false; if (($i + $bytes) > $len) return false; while ($bytes > 1) { $i++; $b = ord($str[$i]); if ($b < 128 || $b > 191) return false; $bytes--; } } } return true; } // end of check_utf8 ?> --was-- In order to check if a string is encoded correctly in utf-8, I suggest the following function, that implements the RFC3629 better than mb_check_encoding(): function check_utf8($str) { $len = strlen($str); for($i = 0; $i < $len; $i++){ $c = ord($str[$i]); if ($c > 128) { if (($c > 247)) return false; elseif ($c > 239) $bytes = 4; elseif ($c > 223) $bytes = 3; elseif ($c > 191) $bytes = 2; else return false; if (($i + $bytes) > $len) return false; while ($bytes > 1) { $i++; $b = ord($str[$i]); if ($b < 128 || $b > 191) return false; $bytes--; } } } return true; } // end of check_utf8 http://php.net/manual/en/function.mb-check-encoding.php

« previous php.notes (#164311) next »