- var_dump: documentation ( source)
- preg_match: documentation ( source)
- array_shift: documentation ( source)
- preg_replace: documentation ( source)
- sprintf: documentation ( source)
<?php
function format_phone($number)
{
$num = preg_replace('/[^0-9]/', '', $number);
$l = strlen($num);
if ($l < 10) {
return false;
}
preg_match('/^([0-9]{3})([0-9]{3})([0-9]{4})([0-9]*)$/', $num, $parts);
array_shift($parts);
$format = '%1$d-%2$d-%3$d';
if ($l > 10) {
$format .= ' x%4$d';
}
return sprintf($format, ... $parts);
}
var_dump(format_phone('8045551234'));