php - 如何在PHP中用加号前缀正数

标签 php regex string number-formatting

我需要设计一个函数来原样返回负数,但如果它已经不存在,则应该在数字的开头添加一个 + 符号。

例子:

Input     Output
----------------
+1         +1
1          +1
-1         -1

它将只获得数字输入。

function formatNum($num)
{
# something here..perhaps a regex?
}

这个函数会在echo/print中被调用多次,所以越快越好。

最佳答案

您可以将正则表达式用作:

function formatNum($num){
    return preg_replace('/^(\d+)$/',"+$1",$num);
}

但我建议 不要 使用 regex 来处理这种微不足道的事情。最好使用sprintf这里是:

function formatNum($num){
    return sprintf("%+d",$num);
}

来自 PHP Manual for sprintf :

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 - 如何在PHP中用加号前缀正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2682397/

相关文章:

php - 在 php Laravel 5 中创建自定义帮助函数的最佳实践是什么?

php - 无法在 Symfony2 应用程序中使用 Sahi/Mink/Behat 上传文件

PHP 包括显示脚本而不是输出

regex - 使用 sed 从挂载获取路径

javascript - String.prototype.replace() 删除破折号和下划线

php - Yii2:是否可以使用 JOIN 同时查询 2 个数据库?

javascript - 使用正则表达式验证 DD-Mon-YYYY 格式的日期

c - 解析所需值的字符串

Javascript::使用变量作为对象 ID 和属性的字符串;

c++ - 在空格处拆分字符串并返回 C++ 中的第一个元素