php - 使用 preg_replace 允许负小数

php - allow negative decimal using preg_replace

我在这样的变量中输入掩码 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

如何得到结果中的负数? 请指教...

更新

You haven't told us your exact desired output

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

您只需要将否定符号添加到您的否定字符中 类。我也可能会做一些其他的调整。

片段:(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)
}