题
我在寻找使用“令牌”的方式,以数字的格式。这需要是有条件的(对于第一几个主导字符)。
示例:
<?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线和含有大量的重复的码。
谁能帮助?
解决方案
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;
$的风格应该优先排序。也许数的初始掩模的长度应表明优先级,在这种情况下可以使用
usort($styles, function($a, $b) {
return strspn($b, '0123456789') - strspn($a, '0123456789');
});
其他提示
只是一个玩具实例
$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
不隶属于 StackOverflow