note 92776 added to function.preg-match
| From: | RPaseur at NationalPres dot org | Date: | Sat, 08 Aug 2009 20:50:51 +0000 |
| Subject: | note 92776 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159215@lists.php.net to get a copy of this message | ||
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
----
Server IP: 64.71.164.2
Probable Submitter: 74.9.128.130
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/92776
Del: integrated -- https://master.php.net/note/delete/92776/integrated
Del: useless -- https://master.php.net/note/delete/92776/useless
Del: bad code -- https://master.php.net/note/delete/92776/bad+code
Del: spam -- https://master.php.net/note/delete/92776/spam
Del: non-english -- https://master.php.net/note/delete/92776/non-english
Del: in docs -- https://master.php.net/note/delete/92776/in+docs
Del: other reasons-- https://master.php.net/note/delete/92776
Reject -- https://master.php.net/note/reject/92776
Search -- https://master.php.net/manage/user-notes.php