← PHP

[php] Eliminar espaço de uma string?

Lida 4885 vezes

Offline

sapovideo 
Membro
Mensagens 295 Gostos 0
Troféus totais: 25
Trófeus: (Ver todos)
Super Combination Combination Topic Starter Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1 100 Posts

Viva... o erro ou a dúvida é absurda... no entanto ou é falta de sono ou falta de paciencia nao consigo sair daqui!

Como tiro o   de uma string?

"1 133.77595"

Já tentei $preco= str_replace(" ",'',trim($preco));
Já tentei $preco= ereg_replace(" ",'',trim($preco));

Com plicas ou aspas... e nada.

O que estou a fazer é um robot que vá buscar o preço de cambio retornado pelo google
http://www.google.com/search?hl=pt-BR&q=990+GBP+to+EUR&btnG=Pesquisar&lr=

Como podem verificar... o valor retornado tem um espaço
990 British pounds = 1 122.43819 Euros

Offline

Gonçalo Martins 
Membro
Mensagens 229 Gostos 0
Troféus totais: 26
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1

Eliminar  

Código: [Seleccione]
$preco = str_replace(' ',"",$preco);


Todos os espaços em branco sem  :

Código: [Seleccione]
$preco = 'ola      isto   é um    teste      ';

$sPattern = '/\s*/m';

$sReplace = '';  

echo $preco . '<br />';
echo preg_replace( $sPattern, $sReplace, $preco );

Offline

sapovideo 
Membro
Mensagens 295 Gostos 0
Troféus totais: 25
Trófeus: (Ver todos)
Super Combination Combination Topic Starter Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1 100 Posts

Código: [Seleccione]
function getValor($preco,$from,$to){
if($from==$to){

}else{
$host = "www.google.com";
$get = "/search?hl=&q=".$preco."+".$from."+to+".$to."";

$header="GET $get HTTP/1.1\r\n";
$header.="Host: $host\r\n";
$header.="Connection: close\r\n\r\n";

$html = get_httpresponse($host,$header);
$data = get_word('><b>'.$preco,'</b></h2>',$html);
$data = explode(" ",$data);
//echo "<pre>".print_r($data)."</pre>";
$preco= $data[sizeof($data)-2];
$preco= ereg_replace('/\s*/m','',$preco);
$preco= str_replace('&nbsp;','',$preco);
}
return number_format($preco,2,',','.');
}

Nao elimina .. já tinha tentado como postei em cima... estranho.
Offline

Thomato 
Membro
Mensagens 4125 Gostos 3
Feedback +2

Troféus totais: 28
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2

Ainda tens um espaço:

$preco= str_replace('&nbsp;','',$preco);
Offline

sapovideo 
Membro
Mensagens 295 Gostos 0
Troféus totais: 25
Trófeus: (Ver todos)
Super Combination Combination Topic Starter Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1 100 Posts

Juro que não dá!

( thomato... a sério? lol )

Offline

Thomato 
Membro
Mensagens 4125 Gostos 3
Feedback +2

Troféus totais: 28
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2

Juro que não dá!

( thomato... a sério? lol )



Apagando esse espaço continua na mesma?
Offline

Gonçalo Martins 
Membro
Mensagens 229 Gostos 0
Troféus totais: 26
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1

Tens razão não funciona....

Experimenta o código abaixo ou vê a solução para o teu problema lá pelo meio...

PS: no teu PHP.ini deverias por 'allow_url_fopen = 0' e utilizar CURL para ir buscar a página...

Está a utilizar a API do Google para conversão de Moedas... o Google têm API para tudo...
http://www.google.com/finance/converter

Bom proveito deve funcionar....  Aqui funcionou... E deste-me post para o meu desactualizado blog  :superlol:


Código: [Seleccione]
<?php
$preco
=Convert('GBP''EUR','990');
if(
$preco!=false){
echo 
$preco;
}
else{echo 
"conversão não possível";}

 function 
Convert($from$to$preco)
    {
        
$url "http://www.google.com/finance/converter?a=$preco&from=$from&to=$to";

        
$data getPage($url);
     
        if(empty(
$data))
            return 
false;
        
        
$dom = new DOMDocument();
        @
$dom->loadHTML($data);
        

        
$return = @$dom->getElementById('currency_converter_result')
                    ->
getElementsByTagName('span')
                    ->
item(0)
                    ->
firstChild
                    
->wholeText;

        
//Elimina &nbsp; converte para float -> o verdadeiro problema estava aqui
        
$return =  (float)$return;        
        if(
$return == )
            return 
false;
        
//tentativas falhadas
//$ret= str_replace($to,'',$return);
    //ret=str_replace('&nbsp;',"",$return);

        return 
$return;
    }
    

    function 
getPage($url)
    {        
    
   if(ini_get('allow_url_fopen') != 1) {
              @
ini_set('allow_url_fopen''1');
          }
           if(
ini_get('allow_url_fopen') != 1) {
              
$ch curl_init();
              
curl_setopt($chCURLOPT_URL,$url);
              
curl_setopt($chCURLOPT_FAILONERROR1);
              
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
              
curl_setopt($chCURLOPT_TIMEOUT3);
              
$data curl_exec($ch);
              
curl_close($ch);
  
            }   
            else {
                
$data file_get_contents($url); 
            }   
      return 
$data;
      }
    
?>
Offline

sapovideo 
Membro
Mensagens 295 Gostos 0
Troféus totais: 25
Trófeus: (Ver todos)
Super Combination Combination Topic Starter Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1 100 Posts

Viva,

Obrigado pela ajuda, não dá na mesma ... mas usando o link que encontraste já dá pk o valor retornado pelos gajos não tem espaço em branco.

Código: [Seleccione]
function getValor($preco,$from,$to){
if($from!=$to){
$host = "www.google.com";
$get = "/finance/converter?a=".$preco."&from=".$from."&to=".$to;
$html = file_get_contents("http://".$host.$get);
$preco = get_word('<span class=bld>','&nbsp;',$html);
}
return number_format ($preco, 2, ',', ' ');
}

Tenho de começar a dar em > PHP 4 ... desconhecia essa classe DOM ... :)

http://www.netlowcost.co.uk/voos.php é para aplicar nisto. Agora é espetar pra lá um google maps , com a rota e já fica impecável.
Offline

Emanuel Santos 
Elite
Mensagens 848 Gostos 2
Feedback +25

Troféus totais: 25
Trófeus: (Ver todos)
Windows User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 4 Level 3 Level 2 Level 1

Experimenta :

$preco= str_replace(html_entity_decode("&nbsp;"),'',$preco);