How to prefix a positive number with plus sign in PHP

You can use regex as:

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

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);
}

From 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.

Leave a Comment