This is a discussion on Reformatting phone number string from user input within the PHP General forums, part of the PHP Programming Forums category; Hi :) I've been working on reformatting a phone number string from user input via a form field. Ultimately, my ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Hi :)
I've been working on reformatting a phone number string from user input via a form field. Ultimately, my goal is to format all phone numbers in the same way regardless of whether a user inputs '(123) 456-7890', '123-456-7890', '123.456.7890', etc. before I insert them into a db. I know I've got a ways to go, but so far, after trying a few things I found in the manual, I'm going in this direction... $patterns[0] = "/\(/"; $patterns[1] = "/\)/"; $patterns[2] = "/-/"; $replacements[0] = ""; $replacements[1] = ""; $replacements[2] = " "; $phone = preg_replace($patterns, $replacements, $phone); This will change '(123) 456-7890' to '123 456 7890' which is what I am after. I'm just wondering if there is a better or more elegant way to handle this before I start trying to cover all the bases? Note: I found a variety of examples in the mailing list archives, but none of them seem to use the method above. Hmmm, does that mean I'm taking the long way around ;) I know I could just copy some examples from there, but I'm trying to use this as a learning opportunity and there seems to be more than one way to skin the cat (no offence to cat lovers ;) TIA for any advice, Verdon |
|
|||
|
Verdon vaillancourt wrote:
> Hi :) > > I've been working on reformatting a phone number string from user input via > a form field. Ultimately, my goal is to format all phone numbers in the same > way regardless of whether a user inputs '(123) 456-7890', '123-456-7890', > '123.456.7890', etc. before I insert them into a db. > > I know I've got a ways to go, but so far, after trying a few things I found > in the manual, I'm going in this direction... > > $patterns[0] = "/\(/"; > $patterns[1] = "/\)/"; > $patterns[2] = "/-/"; > > $replacements[0] = ""; > $replacements[1] = ""; > $replacements[2] = " "; > > $phone = preg_replace($patterns, $replacements, $phone); > > This will change '(123) 456-7890' to '123 456 7890' which is what I am > after. I'm just wondering if there is a better or more elegant way to handle > this before I start trying to cover all the bases? Could do something like this: $phone = preg_replace('/[^0-9]/','',$phone); if(strlen($phone) != 10) { echo "phone number is not valid!"; } $phone = substr($phone,0,3) . ' ' . substr($phone,3,3) . ' ' . substr($phone,-4); Which should cover all of the bases. :) -- ---John Holmes... Amazon Wishlist: www.amazon.com/o/registry/3BEXC84AB3A5E/ PHP|Architect: A magazine for PHP Professionals – www.phparch.com |