Given no one else mentioned this, I would strip out all non-numeric characters from the number. Once done you can use a regex to easily get the numbers, this way any format is valid and pretty much no matter what the user enters you can format it how you want it:
$phone = preg_replace("~[^0-9]~", "", $phone);
preg_match('~([0-9]{3})([0-9]{3})([0-9]{4})~', $phone, $matches);
if (!empty($matches)) {
$display = "<span id='telephone'><span class='spacer'>(" .
$matches[1] . ")</span>" . $matches[2] . "-" . $matches[3] . "</span>";
}else {
$display = "An invalid phone number was entered.";
}
Should do it not matter how the phone number is entered as long as there are 10 digits.
UPDATE
You could also use the preg_replace
technique with substr
and for go the need for preg_match
. This would actually be my preferred solution.
$phone = preg_replace("~[^0-9]~", "", $phone);
if (strlen($phone) == 10) {
$display = "<span id='telephone'><span class='spacer'>(" .
substr($phone,0,3) . ")</span>" . substr($phone,2,3) . "-" . substr($phone,5,4) . "</span>";
}else {
$display = "An invalid phone number was entered.";
}