簡體   English   中英

使用正則表達式刪除貨幣格式

[英]Remove the currency format using regular expression

我正在嘗試找到一條正則表達式來刪除貨幣格式。

我有兩種貨幣值。 一種是USD格式(如1,000.00),另一種是EUR格式(如1.000,00)。 我需要通過刪除逗號和點(如1000.00)將值保存到db中

例如,如果用戶輸入的美元價值為2222.65,則需要替換為2222.65,

如果用戶輸入的歐元值為2.222,65,則還需要替換為2222.65,

一種選擇匹配使用的分隔符的靈魂,然后將其更改為您喜歡的分隔符

<?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]+)$/

可以使用適用於PHP 5 >= 5.3.0, PECL intl >= 1.0.0 NumberFormatter::parse代替復雜的正則表達式。

// 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

假定它們都有小數,但這是最干凈的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM