error in removing space form the return value of convertion of USD to INR using google api in PHP

StackOverflow https://stackoverflow.com/questions/17500165

  •  02-06-2022
  •  | 
  •  

Question

i am trying to convert currency from USD to INR i use the following code:

function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode('"', $data['3']);
$var = $data[0];
$var=str_replace('Indian rupees','',$var);
$var=str_replace(' ', '', $var);
$var = preg_replace('/\s+/', '', $var);
//return floatval($var);
return $var;
}

I want the return value to be free from currency unit and spaces i want a perfect float value. i remove the currency unit by str_replace() but am unable to remove the space because of this conversion to float using floatval() is not working as expected. please help me.

Was it helpful?

Solution

I believe your issues is you have a number with a space in the middle. here is how you can remove the space.

$output = "3 128.71535";

$out = preg_replace("/\s/", "", $output);
echo $out; //outputs: 3128.71535

UPDATE

alternatively you can remove anything other than digits and period.

$output = "3 128.71535";

$out = preg_replace("/[^0-9.]/", "", $output);
echo $out; //outputs: 3128.71535

OTHER TIPS

have tried to use number_format to get your solution, Also you can check detail link as i given here.

you can replace it like

$var = preg_replace('/\s+/', '', $var);
//return floatval($var);
return number_format($var,2);

let me know if i can help you more

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top