note 58193 deleted from function.preg-match by felipe
| From: | felipe@php.net | Date: | Sun, 23 Mar 2008 22:53:49 +0000 |
| Subject: | note 58193 deleted from function.preg-match by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137366@lists.php.net to get a copy of this message | ||
Note Submitter: phpnet_spam at erif dot org
----
Test for valid US phone number, and get it back formatted at the same time:
function getUSPhone($var) {
$US_PHONE_PREG ="/^(?:\+?1[\-\s]?)?(\(\d{3}\)|\d{3})[\-\s\.]?"; //area code
$US_PHONE_PREG.="(\d{3})[\-\.]?(\d{4})"; // seven digits
$US_PHONE_PREG.="(?:\s?x|\s|\s?ext(?:\.|\s)?)?(\d*)?$/"; // any extension
if (!preg_match($US_PHONE_PREG,$var,$match)) {
return false;
} else {
$tmp = "+1 ";
if (substr($match[1],0,1) == "(") {
$tmp.=$match[1];
} else {
$tmp.="(".$match[1].")";
}
$tmp.=" ".$match[2]."-".$match[3];
if ($match[4] <> '') $tmp.=" x".$match[4];
return $tmp;
}
}
usage:
$phone = $_REQUEST["phone"];
if (!($phone = getUSPhone($phone))) {
//error gracefully :)
}