12
2008
Перевод из windows-1251 в UTF-8 если это необходимо
Как определить стоит ли переводить строку в UTF-8 из windows-1251 или она уже в этой кодировке?
Пользуемся следющими функциями:
<?
function cp1251_to_utf8_recursive($data)
{
if (is_array($data))
{
$d = array();
foreach ($data as $k => &$v)
{
$d[cp1251_to_utf8_recursive($k)] = cp1251_to_utf8_recursive($v);
}
return $d;
}
if (is_string($data)) return iconv('cp1251', 'utf-8//IGNORE//TRANSLIT', $data);
if (is_scalar($data) or is_null($data)) return $data;
return $data;
}
function is_utf8(&$data, $is_strict = true)
{
if (is_array($data))
{
foreach ($data as $k => &$v) if (! is_utf8($v, $is_strict)) return false;
return true;
}
elseif (is_string($data))
{
$result = $is_strict ?
preg_replace(‘/(?>[\x09\x0A\x0D\x20-\x7E] # ASCII
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
)*
/sx’, », $data) :
preg_replace(‘/.*/su’, », $data);
}
elseif (is_scalar($data) || is_null($data)) return true;
return false;
}
$str = is_utf8($str) ? $str : cp1251_to_utf8_recursive($str );
?>

Автор