|
Posted by JackM on 05/07/07 23:16
laredotornado@zipmail.com wrote:
> Hi,
>
> Using php 4.4.4, I am looking to parse a US phone number string into 3
> smaller strings -- area code, the first part of the phone number (3
> digits) and the last part of the phone number (4 digits). The only
> given is that there will be 10 digits in the string, but people may
> include spaces, parens, or other characters. These are all strings
> I'd expect
>
> $p = "5558675309";
> $p = "(312) 123-4567";
> $p = "512-234-5678";
This may not be the best option but it's what I sometimes use. You
should be able to modify it for your purposes:
<?php
//process the phone number (USA only) and strip brackets and add dashes
where needed. Output: 555-555-5555
$phone_number = $_POST['phone'];
$dash = "-";
$ext = $_POST['ext'];
$ext1 = " ext";
$pattern = '/^[\(]?(\d{0,3})[\)]?[\s]?[\-]?(\d{3})[\s]?[\-]?(\d{4})$/';
if (preg_match($pattern, $phone_number, $matches)) {
// we have a match, dump sub-patterns to $matches
$phone_number = $matches[0]; // original number
$area_code = $matches[1]; // 3-digit area code
$exchange = $matches[2]; // 3-digit exchange
$number = $matches[3]; // 4-digit number
}
if ($ext == "") {
$phone = $area_code . $dash . $exchange . $dash . $number;
}else{
$phone = $area_code . $dash . $exchange . $dash . $number . $ext1 . $ext;
}
?>
Navigation:
[Reply to this message]
|