2014-01-20 17 views
0

我遇到以下問題。 我需要以下根據用戶(貨幣)設置的環境中顯示:將大括號替換爲內部變量

$sMyPromotion = 'this offer starts at {5000}'; 

// 5000 is the value in my default currency (euros for example) and 
// needs to be converted to the user currency 
// so I have a function that converts : convertRate($Price, $aCurrency) 
// that returns for example: 6000 USD. 

但我堅持就如何採取什麼是大括號和方括號之間,並通過返回的數據進行替換通過convertRate因爲我不舒服的正則表達式,預浸...

我需要的東西呢:

$sOccurency = what is between curly brackets and the brackets; 

$sMyPromotion = Replace $sOccurency with convertRate($sOccurency, $aCurrency); 

所以在這個例子: $ sMyPromotion = '此優惠開始時間:{} 5000' ;

預期結果: $ sMyPromotion ='此優惠始於6000 $';

+0

大括號總是平衡的嗎?它們也可以嵌套嗎? – anubhava

+0

OP,請不要在您的問題標題中放置標籤。 –

回答

1
$sMyPromotion = preg_replace('@{(\d+)}@', '\\1$', $sMyPromotion); 

或使用preg_replace_callback:

$sMyPromotion = preg_replace_callback ('@{(\d+)}@', 
     function ($matches) 
     { 

      return $matches [1] . '$'; 

     }, $sMyPromotion); 
0

爲什麼不把變量放入字符串?像$sMyPromotion = 'this offer starts at '.$valueYouNeed;

0

這個問題有點複雜得多,我想你知道。最明顯的是你必須處理你想要處理的所有貨幣的匯率。

裸陪我 - 我從來沒有寫一個PHP程序之前,但我想嘗試,所以這裏是我的嘗試;)

function TranslateRate($str, $currency) 
{ 
    $def_rate = 100; 

    if (!preg_match('/\{(\d+)\}/', $str, $value)) 
     return $str; // Noting to translate 

    if ($currency = '$') 
    { 
     $dollar_rate=120; 

     $val_rate = ($value[1]/$def_rate); 

     return preg_replace('/(\{\d+\})/', $val_rate*$dollar_rate, $str); 
    } 

    // 'Unknown currency'; 

    return $str; 
} 

echo TranslateRate("this offer starts at {5000}", '$'); 

這是你的翻譯程序的一種非常原始的版本,但它應該給你關於如何繼續的想法。

我甚至不知道如何使用浮點運算的在PHP這樣的速率在美分;)

看到它的工作at phpfiddle

Regards