Jump to content

Convert single integer to double digit values


EchoFool

Recommended Posts

Hey,

 

If i have a string which contains numbers and symbols... such as 1:2:4  (its not always : for the symbol it changes)

 

 

Is there a function that can convert the numbers that are 9 or less to have a 0 infront of them such as:

 

01:02:04

 

(also this is not timestamp format - just normal strings)

Here is an example using preg_replace_callback (taken from the php.net example and modified to match groups of digits and to apply sprintf to pad with leading zeros) -

<?php
$line = "5:14:1+2+5+6+7";
    $line = preg_replace_callback(
        '|\d+|',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return sprintf(\'%02d\',$matches[0]);'
        ),
        $line
    );
echo $line;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.