|
Posted by Toby A Inkster on 05/08/07 15:49
laredotornado@zipmail.com wrote:
> 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.
Are you trying to pull a phone number out of a longer sequence of text
that may contain other numeric things too, or are you trying to parse it
from a dedicated phone number field?
If the former, the two examples already posted look OK. If the latter, then
you can probably afford to be more forgiving. Here is some code that ought
to be more flexible:
<?php
$phone = '2-45 67598 1...2';
$parsed = parse_phone($phone);
print_r($parsed);
function parse_phone ($string, $country='us')
{
if ($country != 'us')
die("Not implemented yet!");
$retval = array();
$string = preg_replace('/[^0-9]/', '', $string);
if (strlen($string)<10)
$retval['Warning'] = "Phone number too short.";
if (strlen($string)>10)
$retval['Warning'] = "Phone number too long. "
. "Possible extension included.";
$retval['AREA'] = substr($string, 0, 3);
$retval['START'] = substr($string, 3, 3);
$retval['FINISH'] = substr($string, 6, 4);
$retval['EXT'] = substr($string, 10);
return $retval;
}
?>
--
Toby A Inkster BSc (Hons) ARCS
http://tobyinkster.co.uk/
Geek of ~ HTML/SQL/Perl/PHP/Python/Apache/Linux
Navigation:
[Reply to this message]
|