如何在PHP中使用加号为正数添加前缀 [英] How to prefix a positive number with plus sign in PHP
问题描述
我需要设计一个函数来返回不变的负数,但是如果该数字已经不存在,则应该在该数字的开头添加一个+
符号.
I need to design a function to return negative numbers unchanged but should add a +
sign at the start of the number if its already no present.
示例:
Input Output
----------------
+1 +1
1 +1
-1 -1
它将仅获得数字输入.
It will get only numeric input.
function formatNum($num)
{
# something here..perhaps a regex?
}
此功能在echo/print
中将被多次调用,所以越快越好.
This function is going to be called several times in echo/print
so the quicker the better.
更新:
谢谢大家的回答.我必须告诉基于sprintf
的解决方案非常快.
Thank you all for the answers. I must tell the sprintf
based solution is really fast.
推荐答案
您可以将regex用作:
You can use regex as:
function formatNum($num){
return preg_replace('/^(\d+)$/',"+$1",$num);
}
但是我建议不使用regex
进行这种琐碎的事情.最好在以下位置使用 sprintf :
But I would suggest not using regex
for such a trivial thing. Its better to make use of sprintf here as:
function formatNum($num){
return sprintf("%+d",$num);
}
来自 sprintf的PHP手册:
一个可选的符号说明符,用于强制在数字上使用符号(-或+).默认情况下,如果数字为负,则仅对数字使用-号. 该说明符也强制正号附加+号,并已在PHP 4.3.0中添加.
An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the - sign is used on a number if it's negative. This specifier forces positive numbers to have the + sign attached as well, and was added in PHP 4.3.0.
这篇关于如何在PHP中使用加号为正数添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!