n1concepts Posted December 13, 2010 Share Posted December 13, 2010 Can someone advise the edit required to include validation of US phone numbers ($phone_number3) when entered with no spaces between the area code and/or prefix. Note: I have working code (regular expression) that validates phone numbers that enclose the area code with parenthesis or having a space, hyphen, or dot between area code, prefix, or last four digits. Examples: all three shown below are validated based on regular expresion (123) 456-7890 123.456.7890 123 456 7890 However, I want to also include the option for 1234567890 (phone number have NO spaces) as valid. I know the edit will be within ( |-|.) using the PIPE but not sure how to denote the "no space" syntax within the regular expression. See the regular expression: $good_phone = "^\(?[0-9]{3}\)?( |-|.)[0-9]{3}(-|.)[0-9]{4}$"; and if you wan to view the entire php snippet // function which validates an American phone number function validate_phone($phone_number) { $good_phone = "^\(?[0-9]{3}\)?( |-|.)[0-9]{3}(-|.)[0-9]{4}$"; if (preg_match("/$good_phone/", $phone_number)) { echo "$phone_number is valid.<br/>"; } else echo "$phone_number is NOT valid.<br/>"; } $phone_number1 = "123.456.7890"; validate_phone($phone_number1); $phone_number2 = "(123) 456-7890"; validate_phone($phone_number2); $phone_number3 ="1234567890"; validate_phone($phone_number3); Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 13, 2010 Share Posted December 13, 2010 You are making it harder than it needs to be. Simply use regex to remove all non-numeric characters and then determine if there are exactly 10 digits. You can then format the phone number as you wish in a consistent format. function validPhone($phone) { $phone = preg_replace("#[^\d]#", '', $phone); if(strlen($phone) != 10) { return false; } return '('.substr($phone, 0, 3).') '.substr($phone, 3, 3).'-'.substr($phone, 6); } validPhone('1234567890') //Output: (123) 456-7890 validPhone('123-456-7890') //Output: (123) 456-7890 validPhone('123.456.7890') //Output: (123) 456-7890 validPhone('(123) 456-7890') //Output: (123) 456-7890 validPhone('123456789') //Output: false validPhone('123-4567') //Output: false Quote Link to comment Share on other sites More sharing options...
n1concepts Posted December 13, 2010 Author Share Posted December 13, 2010 Thanks - I felt there was a better way which why I asked the group - it works perfectly! Problem solved... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.