coupe-r Posted February 3, 2011 Share Posted February 3, 2011 Hi All, I only want to allow phone number in ###-###-####. Anything else I want an error. Here is what I have, which says any number is valid. Function: function checkPhone($number) { if(preg_match('^[0-9]{3}+-[0-9]{3}+-[0-9]{4}^', $number)) { return $number; } else { $items = Array('/\ /', '/\+/', '/\-/', '/\./', '/\,/', '/\(/', '/\)/', '/[a-zA-Z]/'); $clean = preg_replace($items, '', $number); return substr($clean, 0, 3).'-'.substr($clean, 3, 3).'-'.substr($clean, 6, 4); } } Checking Number: $number = '1231231234'; if(checkPhone($number)) { echo $number.' is a valid phone number.'; } else { echo $number.' is not a valid phone number.'; } This should give me the not valid message. Thanks Quote Link to comment Share on other sites More sharing options...
coupe-r Posted February 3, 2011 Author Share Posted February 3, 2011 Sorry, but I got it. I'm already converting the "bad" number to a "good" number. Thanks Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 3, 2011 Share Posted February 3, 2011 That logic is a little backwards. You are trying to list all the characters to replace. It's easier to define the regex expression to replace all characters except numbers. Then you still need to check if there are the right number of digits. I think this will work better for you function checkPhone($number) { //Remove all non digit characters $number = preg_replace("#[^\d]#", '', $number); //If less than 10 digits return false if(strlen($number)<10) { return false; } //Return formatted number return preg_replace("#(\d{3})(\d{3})(\d{4})#", "$1-$2-$3", $number); } 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.