简体   繁体   English

如何使用PHP替换括号并向数字添加减号

[英]How to replace brackets and add minus sign to a number using PHP

I have this variable- $number which may contain different types of number format. 我有这个变量$number ,它可能包含不同类型的数字格式。

Type1: $number=200,000.00 ; Type1: $number=200,000.00 ; Type2: $number=(200,000.00) ; Type2: $number=(200,000.00) ; Type3: $number=(20.50) ; Type3: $number=(20.50) ;

If the number has brackets I want to remove the brackets and add a minus sign on its left side. 如果数字有括号我想删除括号并在其左侧添加减号。

Example: If the number is $number=(200,000.00) ; 示例:如果数字是$number=(200,000.00) ; I want to convert it to -200,000.00 or in case of $number=(20.50) ; 我想将其转换为-200,000.00$number=(20.50) ; I want to convert it to -20.50 but for $number=200,000.00 ; 我想将它转换为-20.50但是$number=200,000.00 ; I want to keep it just the way it is. 我想保持它的方式。

I have tried this preg_replace('/[()^\\d-]+/', '', $number); 我试过这个preg_replace('/[()^\\d-]+/', '', $number); but its not working. 但它不起作用。

Could you please show me how to get this done? 你能告诉我如何完成这项工作吗?

Thanks :) 谢谢 :)

你可以这样做

str_replace(array("(",")"),array("-",""),$number);

I think this should do what you want: 我认为这应该做你想要的:

if (strpos($number, "(") !== false && strpos($number, ")") !== false)
    $number = '-'. trim($number, "()");

Example: http://codepad.org/Yhb80H0v 示例: http//codepad.org/Yhb80H0v

Your $number has to be a string to let PHP "know" about the parentheses. 你的$number必须是一个字符串,让PHP“知道”括号。 Use this code: 使用此代码:

$number = "(1,000.2)";
$number = preg_replace('/\(([0-9,.]+)\)/', '-\1', $number);
print $number;

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

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