Pregunta
¿Cómo saber si un texto tiene codificación utf-8?
Responder esta pregunta por dudin el 2010-03-09
Necesito conocer algún método mediante PHP pasa saber si una cadena de texto tiene la codificación utf-8.
Respuestas
En la clase http://sfToolkit.class.php del Framework Symfony 1.0 encontré el siguiente método el cual he puesto como una función independiente:
function isUTF8($string)
{
for ($idx = 0, $strlen = strlen($string); $idx < $strlen; $idx++)
{
$byte = ord($string[$idx]);
if ($byte & 0x80)
{
if (($byte & 0xE0) == 0xC0)
{
// 2 byte char
$bytes_remaining = 1;
}
else if (($byte & 0xF0) == 0xE0)
{
// 3 byte char
$bytes_remaining = 2;
}
else if (($byte & 0xF8) == 0xF0)
{
// 4 byte char
$bytes_remaining = 3;
}
else
{
return false;
}
if ($idx + $bytes_remaining >= $strlen)
{
return false;
}
while ($bytes_remaining--)
{
if ((ord($string[++$idx]) & 0xC0) != 0x80)
{
return false;
}
}
}
}
return true;
}
por maikel el 2010-03-09



