$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)
如果你有比数字更#,你可以只删除它们,而不是具有功能return false
。如果您的位数多于#,您还可以将它们附加到格式中。