note 92776 deleted from function.preg-match by danbrown
| From: | danbrown@php.net | Date: | Sun, 09 Aug 2009 17:52:13 +0000 |
| Subject: | note 92776 deleted from function.preg-match by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-159250@lists.php.net to get a copy of this message | ||
Note Submitter: RPaseur at NationalPres dot org
----
In regard to http://us2.php.net/manual/en/function.preg-match.php#90503
about parsing phone numbers, this algorithm seems to work well. It performs some basic validation
tests and can return the phone number as a string or as a normalized string.
<?php // RAY_phone_numbers.php - USING USA PHONE NUMBERS
error_reporting(E_ALL);
function strtophone($phone, $format=FALSE)
{
// DISCARD NON-NUMERIC CHARACTERS
$phone = preg_replace('/[^0-9]/', '', $phone);
// DISCARD A LEADING '1' FROM NUMBERS ENTERED LIKE 1-800-555-1212
if (substr($phone,0,1) == '1') $phone = substr($phone,1);
// IF LESS THAN TEN DIGITS, IT IS INVALID
if (strlen($phone) < 10) return FALSE;
// IF IT STARTS WITH '0' OR '1' IT IS INVALID, SECOND DIGIT CANNOT BE
'9'
if (substr($phone,0,1) == '1') return FALSE;
if (substr($phone,0,1) == '0') return FALSE;
if (substr($phone,1,1) == '9') return FALSE;
// ADD OTHER TESTS HERE AS MAY BE NEEDED
// IF NOT FORMATTED
if (!$format) return $phone;
// ISOLATE THE COMPONENTS OF THE PHONE NUMBER
$ac = substr($phone,0,3);
$ex = substr($phone,3,3);
$nm = substr($phone,6,4);
$xt = substr($phone,10);
// STANDARDIZE THE PRINTABLE FORMAT OF THE PHONE NUMBER LIKE 212-555-1212-1234
$formatted_phone = $ac . '-' . $ex . '-' . $nm;
if ($xt != '') $formatted_phone .= '-' . $xt;
return $formatted_phone;
}
// IF ANYTHING IS POSTED?
if (!empty($_POST["phone"]))
{
// VALIDATE PHONE
if (!$phone = strtophone($_POST["phone"], TRUE))
{
echo "BOGUS: {$_POST["phone"]} \n";
} else
{
// SHOW THE FORMATTED PHONE
echo "<br/>$phone\n";
}
}
// END PHP, PUT UP THE FORM TO TEST PHONE NUMBERS
?>
<form method="post">
ENTER A PHONE NUMBER:
<input name="phone" /><br/>
<input type="submit" />
</form>
TRY SOME OF THESE (COPY AND PASTE):
<br/>1-800-5551212
<br/>202-537-7560
<br/>123456789
<br/>703-356-5300 x2048
<br/>(212) 555-1212
<br/>1 + (212) 555-1212
<br/>1 (292) 226-7000