duanfa2014 2012-03-27 09:04
浏览 47
已采纳

使用哈希符号格式化数字的类或函数

What's the easiest way to format a string based on another input string that uses hash symbols, minus, and spaces.

What I have is one string that contains a phone number that might look like this (or has multiple spaces in it):

012-34567890

I have another string that contains the format that the number has to be converted to, this looks like this:

### - ## ## ##

or

## - ### ## ##

or

###-## ## ##

The hash positions must be leading for the formatting of the numbers. I can't seem to think of something that does this...

In some cases (like for international phone numbers) the (, ) and + symbols must be used. In that case the conversion string looks like this (for instance)

+(##)-(#)##-## ## ##

Anyone any ideas?

  • 写回答

1条回答 默认 最新

  • dtebrq0245 2012-03-27 09:21
    关注
    $number = "012-34567890";
    $format1 = "### - ## ## ##";
    $format2 = "+(##)-(#)##-## ## ##";
    $format3 = "## - ### ## ####";
    $format4 = "###-## ## ####";
    
    function formatNumber($number, $format)
    {
        // get all digits in this telephone number
        if (!preg_match_all("~\w~", $number, $matches))
            return false;
    
        // index of next digit to replace #
        $current = 0;
    
        // walk though each character of $format and replace #
        for ($i = 0; $i < strlen($format); $i++)
            if ($format[$i] == "#")
            {
                if (!isset($matches[0][$current]))
                    // more # than numbers
                    return false;
    
                $format[$i] = $matches[0][$current++];
            }
    
        if (count($matches[0]) != $current)
            // more numbers than #
            return false;
    
        return $format;
    }
    
    var_dump(
        formatNumber($number, $format1),
        formatNumber($number, $format2),
        formatNumber($number, $format3),
        formatNumber($number, $format4)
    );
    

    Outputs

    boolean false
    
    string '+(01)-(2)34-56 78 90' (length=20)
    
    string '01 - 234 56 7890' (length=16)
    
    string '012-34 56 7890' (length=14)
    

    If you have got more # than digits, you could just remove them instead of having the the function return false. If you have more digits than # you could also append them to the format.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改