PHP-使用preg_replace允许负十进制

时间:2018-12-19 07:14:33

标签: php regex currency

我在这样的变量200.000,54

中输入了掩码

这是我的php代码

<?php

class MoneyHelper
{
    public function getAmount($money)
    {
        $cleanString = preg_replace('/([^0-9\.,])/i', '', $money);
        $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);

        $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;

        $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
        $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '',  $stringWithCommaOrDot);

        //return (float) str_replace(',', '.', $removedThousandSeparator);

        return [
          'cleanString' => $cleanString,
          'onlyNumbersString' => $onlyNumbersString,
          'separatorsCountToBeErased' => $separatorsCountToBeErased,
          'stringWithCommaOrDot' => $stringWithCommaOrDot,
          'removedThousandSeparator' => $removedThousandSeparator,
          'result' => (float) str_replace(',', '.', $removedThousandSeparator)

        ];

    }
}


$obj = new MoneyHelper;
echo var_dump($obj->getAmount('200.000,54')) ;

结果是:

array (size=6)
 'cleanString' => string '200.000,54' (length=10)
 'onlyNumbersString' => string '20000054' (length=8)
 'separatorsCountToBeErased' => int 1
 'stringWithCommaOrDot' => string '200000,54' (length=9)
 'removedThousandSeparator' => string '200000,54' (length=9)
 'result' => float 200000.54

一切正常,直到我用负数测试此代码。 假设- 200.000,54

然后结果还是一样,

array (size=6)
  'cleanString' => string '200.000,54' (length=10)
  'onlyNumbersString' => string '20000054' (length=8)
  'separatorsCountToBeErased' => int 1
  'stringWithCommaOrDot' => string '200000,54' (length=9)
  'removedThousandSeparator' => string '200000,54' (length=9)
  'result' => float 200000.54

如何获取结果中的负数? 请告知...

更新

  

您没有告诉我们您想要的确切输出结果

我需要:'result' => float -200000.54

1 个答案:

答案 0 :(得分:1)

您只需要在否定的字符类中添加否定符号。我可能还会进行其他一些调整。

摘要:(Full Demo

$cleanString = preg_replace('/[^\d.,-]/', '', $money);
$onlyNumbersString = preg_replace('/[^\d-]/', '', $money);

$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;

$stringWithCommaOrDot = preg_replace('/[,.]/', '', $cleanString, $separatorsCountToBeErased);
$removedThousandSeparator = preg_replace('/[.,](?=\d{3,}$)/', '',  $stringWithCommaOrDot);

输出:

array(6) {
  ["cleanString"]=>
  string(11) "-200.000,54"
  ["onlyNumbersString"]=>
  string(9) "-20000054"
  ["separatorsCountToBeErased"]=>
  int(1)
  ["stringWithCommaOrDot"]=>
  string(10) "-200000,54"
  ["removedThousandSeparator"]=>
  string(10) "-200000,54"
  ["result"]=>
  float(-200000.54)
}
相关问题