Formatting numbers by tokens with php
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?
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');
});
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
精彩评论