php-使用preg_replace允许负十进制
我在变量中有输入掩码,如php-使用preg_replace允许负十进制,php,regex,currency,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);
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')) ;
在我用负数测试这段代码之前,一切都很好。
比如说-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
您只需要将负号添加到求反字符类中。我可能还会做一些其他的调整
代码段:()
输出:
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)
}
十进制是
/^-?[0-9]+(?:\.[0-9]+)?$/
或/^-?\d+(?:\.\d+)$/
可选-
然后是一个数字,然后是可选的
和一些其他数字。^
开始和$
结束确保您不会部分匹配,例如123foo
至于问题,您至少在这里将其剥离2倍preg\u replace('/([^0-9\,]))/我的“
没有减号,所以它被删除了,下一行的另一个时间。
不需要在字符类中转义。请查看我的更新
$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)
}