2013-07-31 90 views
1

我正試圖找到一塊正則表達式來刪除貨幣格式。使用正則表達式刪除貨幣格式

我有兩種類型的貨幣值。一種是1,000.00美元的格式,另一種是1000,000歐元的歐元格式。我需要同時去除逗號到數據庫保存的價值和點狀1000.00

例如,如果用戶輸入像2,222.65美元的價值,它需要更換至2222.65,

如果用戶進入在歐元價值像2.222,65它也需要更換至2222.65,

回答

1

而是複雜的正則表達式,使用NumberFormatter::parse可供PHP 5 >= 5.3.0, PECL intl >= 1.0.0

// German format 
$fmt = new NumberFormatter('de_DE', NumberFormatter::DECIMAL); 
$num = "1.234.567,891"; 
echo $fmt->parse($num)."<br>\n"; 

// USD format 
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL); 
$num = "9,876,543.012"; 
echo $fmt->parse($num)."<br>\n"; 

OUTPUT:

1234567.891 
9876543.012 
+0

可以skipp的郎代碼,使其自動,所以你不到風度需要知道什麼格式,用戶要使用時,用戶可能會瑞典和使用「1 234 567,89」 –

+0

我認爲locale是一個必需的字符串,用於爲特定區域設置解析正確格式的字符串。 – anubhava

+0

不客氣。 – anubhava

1

一個soultion以匹配什麼用分離器,並將其更改爲你prefere

<?php 

    /* split input in 3 parts: integer, separator, decimals */ 
    if(preg_match('#^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$#', $input, $matches)) 
    { 
     /* clean integer and append decimals with your own separator */ 
     $number = ((int) preg_replace('#[^0-9]+#', '', $matches['integer']) . '.' . $matches['decimals'] 
    } 
    else 
    { 
     $number = (int) preg_replace('#[^0-9]+#', '', $input); 
    } 
?> 

公告一:我希望有我在#中插入正則表達式,因爲我使用/在我的內部正則表達式,如果 喜歡YPU /你可以使用/[^0-9]+//^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$/

0

這假定他們都有小數,但它是最乾淨的。

$str = "2,222.65"; 
    $clean = preg_replace('/[^\d]/', '', $str); 
    $clean = substr($clean, 0,-2) . "." . substr($clean,-2); 
+0

謝謝你。但請檢查輸入2,222.765 –