Skip to content

Instantly share code, notes, and snippets.

@edinella
Last active December 16, 2015 03:59
Show Gist options
  • Save edinella/5374087 to your computer and use it in GitHub Desktop.
Save edinella/5374087 to your computer and use it in GitHub Desktop.
Detecta encoding de uma string, testando as opções informadas, com PHP4+ e iconv
<?php
/**
* Detecta encoding de uma string, testando as opções informadas
* @param string $string
* @param array $opcoes
* @return string|null
*/
function obtemEncoding($string, $opcoes=array('UTF-8', 'ISO-8859-1', 'WINDOWS-1251'))
{
if(!empty($opcoes))
foreach($opcoes as $codificacao)
if(md5(iconv($codificacao, $codificacao, $string)) == md5($string))
return $codificacao;
return null;
}
// string a ser convertida
$str = 'xx';
// converte
$encodingOrigem = obtemEncoding($str);
$encodingDestino = 'ISO-8859-1';
$stringConvertida = iconv($encodingOrigem, $encodingDestino, $str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment