PDA

View Full Version : Regex for phone numbers and zip codes


daveofwar
10-18-2007, 06:30 PM
Hello codingforums

Does anyone know the reg ex for phone numbers which include special chars like () - or any other number used by people to seperate the numbers and also the regex for a zip code


Thanks for the help in advance

kbluhm
10-18-2007, 07:08 PM
One quick and fairly fail-safe way to do it is to just drop anything that's not a number, then get the length. This way will avoid having to parse stuff like spaces, hyphens, parenthesis, etc... since we know the real meat of zip codes and phone numbers are digits and digits alone.
<?php

// zip codes will be 5 or 9 digits, ie: 12345 or 12345-6789
function is_zipcode( $zipcode )
{
$length = strlen( preg_replace( '/\D/', '', $zipcode ) );
return ( $length === 5 OR $length === 9 );
}

// phone numbers will be 10 digits, ie: (123) 456-7890
function is_phone( $phone )
{
return strlen( preg_replace( '/\D/', '', $phone ) ) === 10;
}

?>

daveofwar
10-18-2007, 07:45 PM
O yea good idea thanks