【问题标题】:Replace a string on php替换php上的字符串
【发布时间】:2010-10-04 07:21:30
【问题描述】:

我正在使用将 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 您可以在第二个数字之后看到一个空格。

我只是想删除它。我需要在函数中做哪些修改。

提前致谢

【问题讨论】:

    标签: php regex string replace


    【解决方案1】:

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

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

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

    您可以删除其余字符:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        strtr() 删除一个字符 (it's optimized for that) 更快,所以你可以这样做

        strtr($str, " ", "");
        

        【讨论】:

          猜你喜欢
          • 2012-04-27
          • 1970-01-01
          • 1970-01-01
          • 2013-11-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-15
          相关资源
          最近更新 更多