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

Php 类或函数使用哈希符号格式化数字,php,function,class,string-formatting,phone-number,Php,Function,Class,String Formatting,Phone Number,基于另一个使用散列符号、减号和空格的输入字符串格式化字符串的最简单方法是什么 我有一个字符串,其中包含一个电话号码,可能看起来像这样(或者有多个空格): 我有另一个字符串,其中包含数字必须转换为的格式,如下所示: ### - ## ## ## ## - ### ## ## 或 或 哈希位置必须是数字格式的前导。我似乎想不出有什么东西能做到这一点 在某些情况下(如国际电话号码),必须使用(、)和+符号。在这种情况下,转换字符串如下所示(例如) 有人有什么想法吗 $number = "012-3

基于另一个使用散列符号、减号和空格的输入字符串格式化字符串的最简单方法是什么

我有一个字符串,其中包含一个电话号码,可能看起来像这样(或者有多个空格):

我有另一个字符串,其中包含数字必须转换为的格式,如下所示:

### - ## ## ##
## - ### ## ##

哈希位置必须是数字格式的前导。我似乎想不出有什么东西能做到这一点

在某些情况下(如国际电话号码),必须使用(、)和+符号。在这种情况下,转换字符串如下所示(例如)

有人有什么想法吗

$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)
);
如果您得到的#个以上的数字,您可以删除它们,而不是让函数
返回false
。如果数字多于#,也可以将其附加到格式中

###-## ## ##
+(##)-(#)##-## ## ##
$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)
);
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)