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.

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

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效