views:

50

answers:

2

I'm looking for a way to format numbers using "tokens". This needs to be conditional (for the first few leading characters).

Example:

<?php
 $styles=array('04## ### ###','0# #### ####','13# ###','1800 ### ###');
 format_number(0412345678); /*should return '0412 345 678'*/
 format_number(0812345678); /*should return '08 1234 5678'*/
 format_number(133622); /*should return '133 622'*/
 format_number(1800123456); /*should return '1800 123 456'*/
?>

Incase you haven't guessed, my use of this is to format Australian phone numbers, dependent on their 'type'.

I have a PHP function that does this, but it is ~114 lines and contains a lot of repeated code.

Can anyone help?

+1  A: 

just a toy example

$number="0412345678";
$styles=array('04## ### ###','0# #### ####','13# ###','1800 ### ###');
$whatiwant = preg_grep("/04/i",$styles);  #04 is hardcoded. 
$s = explode(" ",$whatiwant[0]);
$count= array_map(strlen,$s);
$i=0;
foreach($count as $k){
  print substr($number,$i,$k)." ";
  $i=$k;
}

output

$ php test.php
0412 345 234 
ghostdog74
I don't think it works properly..from: 0412345678, 0891234567, 133622, 1800321456 and 1300321456it's outputting:0412 345 234, 0891 234 123, ,1336 22 622, 1800 321 032, 1300 321 032
Adam D
@Adam, I believe the whole point was to show how you could correctly grab the style that matches the `$number` format.
Anthony Forloney
What I'm trying to do needs to rely on as little hard coding of the formatting as possible as the 'styles' will be coming from a database (for user customisation)
Adam D
+1  A: 
foreach ($styles as $style) {
    $pattern = sprintf(
        "/^%s$/D",
        str_replace(array(' ', '#'), array('', '\d'), $style)
    );

    if (preg_match($pattern, $phoneNumber)) {
        return vsprintf(
            preg_replace('/\S/', '%s', $style),
            str_split($phoneNumber)
        );
    }
}
return $phoneNumber;

$styles should be ordered by precedence. Maybe the length of the initial mask of numbers should dictate precedence, in which case you could use

usort($styles, function($a, $b) {
    return strspn($b, '0123456789') - strspn($a, '0123456789');
});
chris
I did not know about `str_split` yet. Thanks! I missed your answer when I posted mine, which I have now deleted.
janmoesen
Spot on mate. Thanks :)
Adam D
Actually, I have one more question which is related. If a phone number passed is longer than a number 'style', but matches the required format (ie: 1800123456233); what would be required to make the "233" (or any other numbers) at the end be printed as an "extension" ie: "1800 123 456 #233"?
Adam D