gunnarrr gunnarrr - 4 months ago 24
PHP Question

PHP Number Format (Construction Station)

I'm trying to format construction stationing, but I can't figure out how to get the preg_replace function to accept a variable number of leading characters. The format is [variable leading characters]+XX.XX This is what I'm using right now:

Input:

0
20
160
5005.5
30096.56
1000000000.00


Function:

function formatStation($number){
$number = sprintf('%06.2f', $number);

$number = preg_replace('/([0-9])([0-9]{2})/', '$1+$2', $number);
return $number;
}


Output:

0+00.00
0+20.00
1+60.00
5+005.50 <-
3+0096.56 <-
1+000000000.00 <-


The correct output should be:

0+00.00
0+20.00
1+60.00
50+05.50 <-
300+96.56 <-
10000000+00.00 <-

Answer

Here is the code, which work according to your assignment:

function formatStation($number){
    $number = sprintf('%06.2f', $number);

    $number = preg_replace('/([0-9])([0-9]{2}\.[0-9]{2})/', '$1+$2', $number);
    return $number;
} 

Here you can test it.

Comments