替换php上的字符串

时间:2010-10-04 07:21:30

标签: php regex string replace

我正在使用将INR转换为USD的功能。我正在使用这个功能:

    function convertCurrency($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];
        if($to_Currency == 'USD')
            return round($var, 2);
        else
            return round($var, 0);
    }

当我通过10 INR时,它工作正常。 但是当我传递500000 INR时,结果是11 312您可以在第二个数字后看到一个空格。

我只想删除它。我需要在函数中做什么修改。

提前致谢

3 个答案:

答案 0 :(得分:0)

您可以使用正则表达式,删除不是数字的所有内容:

$amount = preg_replace("[^0-9.]", "", $amount);

答案 1 :(得分:0)

您可以使用str_replce从最终字符串中删除所有空格:

$str = str_replace(' ','',$str);

或者,最终结果中唯一允许的字符是数字和句点(.)。

您可以删除其余的字符:

$str = preg_replace('/[^\d.]/','',$str);

答案 2 :(得分:0)

strtr()删除一个字符(it's optimized for that)的速度更快,因此您可以

strtr($str, " ", "");
相关问题