Splitting up a phone number in php
Ok so i have a variable $phone which contains the string (407)888-9999 and I have this code
if($phone != ''){ $phone = "<span id='tel开发者_开发百科ephone'>{$phone}</span>";}
return $phone;
This works fine but now the client wants to have a some padding in between the area code and the next three numbers. So i need the code to be like this
<span id='telephone'><span class='spacer'>(407)</span>888-9999</span>";
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 forego 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.";
}
Do you know for sure that the string is properly formatted? If so, you can break it up into substrings:
$phone = "<span id='telephone'><span class='spacer'>{substr($phone, 0, 5)}</span>{substr($phone, 5, 8)}";
You can do:
$input = "(407)888-9999";
$area_code = '';
$ph_num = $input;
if(strpos($input,')') !== false) { // if area-code is present.
list($area_code,$ph_num) = explode(')',$input);
$area_code .= ')';
}
Iff the phone number is always in the same format, you can split it with:
list($area,$phone1,$phone2) = sscanf($phone,'(%d)%d-%d');
or
sscanf($phone,'(%d)%d-%d',$area,$phone1,$phone2)
You need regular expressions:
<?php
preg_match("/(\([^\)*]\))(.*)/", $phone, &$matches);
var_dump($matches);
print "<span id='telephone'><span class='spacer'>({$matches[1]})</span>$matches[2]</span>";
?>
You can just use a simple str_replace like this, as long as you're sure the phone numbers have brackets around the area code ...
$phone = "(902)555-1234";
if($phone != ''){
$phone = str_replace(")", ") ",$phone);
$phone = "<span id='telephone'>{$phone}</span>";
}
return $phone;
精彩评论