繁体   English   中英

使用preg_replace括号中的负值格式

[英]Negative value format with in parentheses using preg_replace

我想要一个使用preg_replace转换的正则表达式

=> -1121234.56 to (1,121,234.56)
=> -1121 to (1,121.00)
=> 1121 to 1,121.00

现在我用过了

$number = -12121234.56;
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);

O/P -12,121,234.56

我也想要上述功能。

你可以使用number_format()

function myformat($nr)
{
    $nr = number_format($nr, 2);
    return $nr[0] == '-' ? "(" . substr($nr, 1) . ")" : $nr;
}

myformat(-1121234.56);
myformat(-1121);
myformat(1121);

另请参见: number_format()

我可以使用preg_replacenumber_format来解决

$replace = preg_replace(
               '/(-)([\d\.\,]+)/ui',  
               '($2)',                          
               number_format($number,2,'.',',')       
           );

一些测试:

$number                     $replace
12121234.56                 12,121,234.56
-12121234.56                (12,121,234.56)
-1234567.89                 (1,234,567.89)

我希望这可以帮到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM