使用substr格式化电话号码

时间:2012-02-18 17:06:10

标签: php smarty

我想根据手机号码或固定电话/家用电话格式化电话号码。澳大利亚的手机号码从04开始;我可以这样做:

{if (substr($number, 0,2) == '04'}

apply this format #### ### ###

{else}

apply this format (##) #### #### or #### ###

取决于区域代码是否输入。

我将此应用于模板/ html页面,我遇到了一些问题......手机号码被识别并格式化,但其他数字不起作用....这就是我做的事情

{if $listing.user[$v.caption]|substr:0:2== '04'}
{$listing.user[$v.caption]|substr:0:4} 
{$listing.user[$v.caption]|substr:4:3} 
{$listing.user[$v.caption]|substr:7}

{elseif $listing.user[$v.caption]|strlen>8}
({$listing.user[$v.caption]|substr:0:2}) 
{$listing.user[$v.caption]|substr:2:4} 
{$listing.user[$v.caption]|substr:6}

{else}
{$listing.user[$v.caption]|substr:0:4} 
{$listing.user[$v.caption]|substr:4:4}
{/if}

1 个答案:

答案 0 :(得分:0)

你的if语句可以解决问题:

//if the first two digits are `04` then use the format: #### ### ###
if (substr($number, 0, 2) == '04') {
    $number = substr($number, 0, 4) . ' ' . substr($number, 4, 3) . ' ' . substr($number, 7);

//otherwise do more checks on the number
} else {

    //if the number is longer than seven digits then use the format: (##) #### ####
    if (strlen($number) > 7) {
        $number = '(' + substr($number, 0, 2) . ') ' . substr($number, 2, 4) . ' ' . substr($number, 6);

    //otherwise use the format: #### ###
    } else {
        $number = substr($number, 0, 4) . ' ' . substr($number, 4, 3);
    }
}