Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Carcleo

[Resolvido] string_replace reage estranho

Recommended Posts

Pessoal, peguei essa função que estava em asp e passei para php na net com a finalidade de converter alguns caracters ascii para utf8.


<?php
function ReformatCSVString($strInput)
{ 

       // Replace accented characters 
       $strInput = str_replace("\u00c0", "À", $strInput);
       $strInput = str_replace("\u00c1", "Á", $strInput);
       $strInput = str_replace("\u00c2", "Â", $strInput);
       $strInput = str_replace("\u00c3", "Ã", $strInput);
       $strInput = str_replace("\u00c4", "Ä", $strInput);
       $strInput = str_replace("\u00c5", "Å", $strInput);
       $strInput = str_replace("\u00c6", "Æ", $strInput);
       $strInput = str_replace("\u00c7", "Ç", $strInput);
       $strInput = str_replace("\u00c8", "È", $strInput);
       $strInput = str_replace("\u00c9", "É", $strInput);
       $strInput = str_replace("\u00ca", "Ê", $strInput);
       $strInput = str_replace("\u00cb", "Ë", $strInput);
       $strInput = str_replace("\u00cc", "Ì", $strInput);
       $strInput = str_replace("\u00cd", "Í", $strInput);
       $strInput = str_replace("\u00ce", "Î", $strInput);
       $strInput = str_replace("\u00cf", "Ï", $strInput);
       $strInput = str_replace("\u00d1", "Ñ", $strInput);
       $strInput = str_replace("\u00d2", "Ò", $strInput);
       $strInput = str_replace("\u00d3", "Ó", $strInput);
       $strInput = str_replace("\u00d4", "Ô", $strInput);
       $strInput = str_replace("\u00d5", "Õ", $strInput);
       $strInput = str_replace("\u00d6", "Ö", $strInput);
       $strInput = str_replace("\u00d8", "Ø", $strInput);
       $strInput = str_replace("\u00d9", "Ù", $strInput);
       $strInput = str_replace("\u00da", "Ú", $strInput);
       $strInput = str_replace("\u00db", "Û", $strInput);
       $strInput = str_replace("\u00dc", "Ü", $strInput);
       $strInput = str_replace("\u00dd", "Ý", $strInput);

       //Now lower case accents 		
       $strInput = str_replace("\u00df", "ß", $strInput);
       $strInput = str_replace("\u00e0", "à", $strInput);
       $strInput = str_replace("\u00e1", "á", $strInput);
       $strInput = str_replace("\u00e2", "â", $strInput);
       $strInput = str_replace("\u00e3", "ã", $strInput);
       $strInput = str_replace("\u00e4", "ä", $strInput);
       $strInput = str_replace("\u00e5", "å", $strInput);
       $strInput = str_replace("\u00e6", "æ", $strInput);
       $strInput = str_replace("\u00e7", "ç", $strInput);
       $strInput = str_replace("\u00e8", "è", $strInput);
       $strInput = str_replace("\u00e9", "é", $strInput);
       $strInput = str_replace("\u00ea", "ê", $strInput);
       $strInput = str_replace("\u00eb", "ë", $strInput);
       $strInput = str_replace("\u00ec", "ì", $strInput);
       $strInput = str_replace("\u00ed", "í", $strInput);
       $strInput = str_replace("\u00ee", "î", $strInput);
       $strInput = str_replace("\u00ef", "ï", $strInput);
       $strInput = str_replace("\u00f0", "ð", $strInput);
       $strInput = str_replace("\u00f1", "ñ", $strInput);
       $strInput = str_replace("\u00f2", "ò", $strInput);
       $strInput = str_replace("\u00f3", "ó", $strInput);
       $strInput = str_replace("\u00f4", "ô", $strInput);
       $strInput = str_replace("\u00f5", "õ", $strInput);
       $strInput = str_replace("\u00f6", "ö", $strInput);
       $strInput = str_replace("\u00f8", "ø", $strInput);
       $strInput = str_replace("\u00f9", "ù", $strInput);
       $strInput = str_replace("\u00fa", "ú", $strInput);
       $strInput = str_replace("\u00fb", "û", $strInput);
       $strInput = str_replace("\u00fc", "ü", $strInput);
       $strInput = str_replace("\u00fd", "ý", $strInput);
       $strInput = str_replace("\u00ff", "ÿ", $strInput);

       return $strInput; 

}

print ReformatCSVString("Muria\u00e9");
?>

Chemei ela com a string

 

"Muria\u00e9"

 

esperando retorno

 

"Muriaé"

 

Conforme string_replace.

 

Mas o retorno foi

 

"Muriaé"

 

Porque disso?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Você deve verificar o formato do arquivo que está trabalhando. Você pode salvar o arquivo tanto em UTF-8 como em ISO-8859-1.

 

Abra em um editor HTML (notepad++ é bem indicado), mude a codificação do arquivo, e salve novamente.

 

Também verifique o cabeçalho que está usando. O arquivo pode estar setado de uma forma, enquanto o cabeçalho de outra. Como padrão, aonde eu trabalho, usamos UTF-8.

Compartilhar este post


Link para o post
Compartilhar em outros sites

sobre o str_replace, ao invés de repetir o script para cada caracter, utilize arrays como parâmetros:

http://forum.imasters.com.br/topic/304199-funcoes-que-corrige-acentos/page__view__findpost__p__1119114

 

quanto ao encode do arquivo csv, acho que nem precisaria fazer o str_replace... talvez somente a conversão dos dados usando as funções mbstring

Compartilhar este post


Link para o post
Compartilhar em outros sites

Entendi, obrigado.

 

Mas, no meu caso, estava faltando o cabeçalho de indicação utf-8 para o html:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sem título</title>
</head>
<body>

<?php 
include('phpQuery-onefile.php');

function simple_curl($url,$post=array(),$get=array()){
$url = explode('?',$url,2);
if(count($url)===2){
	$temp_get = array();
	parse_str($url[1],$temp_get);
	$get = array_merge($get,$temp_get);
}

$ch = curl_init($url[0]."?".http_build_query($get));
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec ($ch);
}

//$cep = $_GET['cep'];
$cep = 36880000;

$html = simple_curl('http://m.correios.com.br/movel/buscaCepConfirma.do',array(
'cepEntrada'=>$cep,
'tipoCep'=>'',
'cepTemp'=>'',
'metodo'=>'buscarCep'
));

phpQuery::newDocumentHTML($html, $charset = 'utf-8');

//include "../global/funcoes_php/asciiToutf8.php";

$dados = 
array(
'logradouro'=> trim(pq('.caixacampobranco .resposta:contains("Logradouro: ") + .respostadestaque:eq(0)')->html()),
'bairro'=> trim(pq('.caixacampobranco .resposta:contains("Bairro: ") + .respostadestaque:eq(0)')->html()),
'cidade/uf'=> trim(pq('.caixacampobranco .resposta:contains("Localidade / UF: ") + .respostadestaque:eq(0)')->html()),
'cep'=> trim(pq('.caixacampobranco .resposta:contains("CEP: ") + .respostadestaque:eq(0)')->html())
);

$dados['cidade/uf'] = explode('/',$dados['cidade/uf']);
$dados['cidade'] = trim($dados['cidade/uf'][0]);
$dados['uf'] = trim($dados['cidade/uf'][1]);

print $dados['cidade']."-".$dados['uf'];
?>

</body>
</html>

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Veja só que, usando o cabeçalho html, não foi necessário usar a função.

Ah! Eu pensei que mesmo com o cabeçalho você faria uso da função no seu projeto!

Compartilhar este post


Link para o post
Compartilhar em outros sites

não, não.

 

Mas, deixa eu incomodar mais um pouco.

Tenho o código abaixo:

<?php
$link = "http://www.geoplugin.net/php.gp?ip=".$_SERVER["REMOTE_ADDR"];

$data =  unserialize(file_get_contents($link));

$estado = $data["geoplugin_region"];

if($estado = "Distrito Federal" ){$regiao = "CENTRO-OESTE";}
else if($estado = "Goiás" ){$regiao = "CENTRO-OESTE";}
else if($estado = "Mato Grosso" ){$regiao = "CENTRO-OESTE";}
else if($estado = "Mato Grosso do Sul" ){$regiao = "CENTRO-OESTE";}

else if($estado = "Acre" ){$regiao = "NORTE";}
else if($estado = "Distrito Federal" ){$regiao = "NORTE";}
else if($estado = "Amapá" ){$regiao = "NORTE";}
else if($estado = "Amazonas" ){$regiao = "NORTE";}
else if($estado = "Pará" ){$regiao = "NORTE";}
else if($estado = "Rondônia" ){$regiao = "NORTE";}
else if($estado = "Roraima" ){$regiao = "NORTE";}
else if($estado = "Tocantins" ){$regiao = "NORTE";}

else if($estado = "Alagoas" ){$regiao = "NORDESTE";}
else if($estado = "Bahia" ){$regiao = "NORDESTE";}
else if($estado = "Ceará" ){$regiao = "NORDESTE";}
else if($estado = "Maranhão" ){$regiao = "NORDESTE";}
else if($estado = "Paraíba" ){$regiao = "NORDESTE";}
else if($estado = "Pernambuco" ){$regiao = "NORDESTE";}
else if($estado = "Piauí" ){$regiao = "NORDESTE";}
else if($estado = "Rio Grande do Norte" ){$regiao = "NORDESTE";}
else if($estado = "Sergipe" ){$regiao = "NORDESTE";}

else if($estado = "Espírito Santo" ){$regiao = "SUDESTE";}
else if($estado = "Minas Gerais" ){$regiao = "SUDESTE";}
else if($estado = "Rio de Janeiro" ){$regiao = "SUDESTE";}
else if($estado = "São Paulo" ){$regiao = "SUDESTE";}

else if($estado = "Paraná" ){$regiao = "SUL";}
else if($estado = "Santa Catarina" ){$regiao = "SUL";}
else if($estado = "Rio Grande do Sul" ){$regiao = "SUL";}

else 
{
 echo "<table align=\"center\" width=\"600px\" height=\"300px\"><tr><td align=\"center\" valign=\"middle\">";
 echo "Desculpe, não conseguimos validar a região do Brasil a qual você se encontra";
 echo "<br />";
 echo "Tentando outra vez em 10 segundos...";
 echo "</td></tr></table>";
 header("refresh: 10; url=index2.php"); 
}

header ("Location:logon.php?acao=login&regiao=$regiao")
?>

A ideia aqui é pegar o estado do usuário pelo ip e verificar, em um consulta ao banco, qual região que ele pertence e qual o percentual de desconto.

 

Mas, esses dados não são minha dificuldade.

 

o problema é que, se der um print na variavel(no começo do código) $estado. Partindo do meu ip, retorno Minas Gerais (ja testei esse print).

 

Mas, ao entrar nos if's e if else's da vida, ela informa no final que a variavel região é CENTRO_OESTE e não SUDESTE.

 

Porque será?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Você está usando "=" nos if´s, equanto deveria usar "=="!

 

Um "=" atribui o valor, já dois "="(==) compara os valores, o correto seria:

 

<?php
$link = "http://www.geoplugin.net/php.gp?ip=".$_SERVER["REMOTE_ADDR"];

$data =  unserialize(file_get_contents($link));

$estado = $data["geoplugin_region"];

if($estado == "Distrito Federal" ){$regiao = "CENTRO-OESTE";}
else if($estado == "Goiás" ){$regiao = "CENTRO-OESTE";}
else if($estado == "Mato Grosso" ){$regiao = "CENTRO-OESTE";}
else if($estado == "Mato Grosso do Sul" ){$regiao = "CENTRO-OESTE";}

else if($estado == "Acre" ){$regiao = "NORTE";}
else if($estado == "Distrito Federal" ){$regiao = "NORTE";}
else if($estado == "Amapá" ){$regiao = "NORTE";}
else if($estado == "Amazonas" ){$regiao = "NORTE";}
else if($estado == "Pará" ){$regiao = "NORTE";}
else if($estado == "Rondônia" ){$regiao = "NORTE";}
else if($estado == "Roraima" ){$regiao = "NORTE";}
else if($estado == "Tocantins" ){$regiao = "NORTE";}

else if($estado == "Alagoas" ){$regiao = "NORDESTE";}
else if($estado == "Bahia" ){$regiao = "NORDESTE";}
else if($estado == "Ceará" ){$regiao = "NORDESTE";}
else if($estado == "Maranhão" ){$regiao = "NORDESTE";}
else if($estado == "Paraíba" ){$regiao = "NORDESTE";}
else if($estado == "Pernambuco" ){$regiao = "NORDESTE";}
else if($estado == "Piauí" ){$regiao = "NORDESTE";}
else if($estado == "Rio Grande do Norte" ){$regiao = "NORDESTE";}
else if($estado == "Sergipe" ){$regiao = "NORDESTE";}

else if($estado == "Espírito Santo" ){$regiao = "SUDESTE";}
else if($estado == "Minas Gerais" ){$regiao = "SUDESTE";}
else if($estado == "Rio de Janeiro" ){$regiao = "SUDESTE";}
else if($estado == "São Paulo" ){$regiao = "SUDESTE";}

else if($estado == "Paraná" ){$regiao = "SUL";}
else if($estado == "Santa Catarina" ){$regiao = "SUL";}
else if($estado == "Rio Grande do Sul" ){$regiao = "SUL";}

else 
{
        echo "<table align=\"center\" width=\"600px\" height=\"300px\"><tr><td align=\"center\" valign=\"middle\">";
        echo "Desculpe, não conseguimos validar a região do Brasil a qual você se encontra";
        echo "<br />";
        echo "Tentando outra vez em 10 segundos...";
        echo "</td></tr></table>";
        header("refresh: 10; url=index2.php"); 
}

header ("Location:logon.php?acao=login&regiao=$regiao")
?>

 

No seu caso, recomendo o uso do switch!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.