1

我正在寻找一种使用“令牌”格式化数字的方法。这需要是有条件的(对于前几个主角)。

例子:

<?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'*/
?>

如果您没有猜到,我的用途是格式化澳大利亚电话号码,具体取决于它们的“类型”。

我有一个 PHP 函数可以做到这一点,但它是 ~114 行并且包含很多重复的代码。

任何人都可以帮忙吗?

4

2 回答 2

1

只是一个玩具例子

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

输出

$ php test.php
0412 345 234 
于 2010-03-16T04:24:11.583 回答
1
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 应该按优先级排序。也许数字的初始掩码的长度应该决定优先级,在这种情况下你可以使用

usort($styles, function($a, $b) {
    return strspn($b, '0123456789') - strspn($a, '0123456789');
});
于 2010-03-16T07:32:02.077 回答