Forum Moderators: coopster
//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
//Replaces all those with (333) 444-5555
$phone1 = preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $_POST['PHONE1']);
$phone2 = preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $_POST['PHONE2']);
$phone3 = preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $_POST['PHONE3']);
$phones = $phone1 ."|". $phone2 ."|". $phone3;
// $phones = "0123456789|0123456789|0123456789";
$phone = $_POST['PHONE1'].$_POST['PHONE2'].$_POST['PHONE3'];
// now make sure $phone only has numbers
$phone = preg_replace("|(^[0-9]|", "", $phone);
// check if it still has 10 digits
if(strlen($phone) < 10)
exit("Phonenumber is to short");
$delimiter = '-';
list ($formatted_phone,$errs) = check_phone('PHONE',3,3,4,$delimiter);
if ($errs) {
// should actually return to form with error, but
echo "<p>Errors:</p></ul>$errs</ul>";
exit;
}
else { echo $formatted_phone; }
function check_phone($name,$len1,$len2,$len3,$delim=null) {
$phone_errors=$formatted=null;
// Field lengths, alter as needed
$flengths = Array($len1,$len2,$len3);
//
for ($i=1;$i<=3;$i++) {
$nm=$name.$i;
$index = $flengths[$i-1];
if (isset($_POST[$nm])) {
// Just cleanse it, errors confuse people,
// only error if you have to. A space, for example.
$_POST[$nm] = preg_replace('/[^\d]/','',$_POST[$nm]);
if (! (strlen($_POST[$nm])==$index)) {
$phone_errors .= "<li>Please enter $index numbers for phone field $i.</li>";
}
$formatted .= $_POST[$nm];
if ($i<3) { $formatted .= $delim; }
}
else { $phone_errors .= "<li>Phone field $i is blank.</li>"; }
}
return Array($formatted,$phone_errors);
}