tags:

views:

876

answers:

3

I have a simple text field for "Phone Number" in a contact form on a client's website. The formmail script returns whatever the user types into the field. For example, they'll receive "000-000-0000", "0000000000", (000) 000-000, etc. The client would like to receive all phone numbers in this form: 000-000-0000. Can someone provide a simple script that would strip out all extraneous punctuation, then re-insert the dashes?

I'm not a programmer, just a designer so I can't provide any existing code for anyone to evaluate, though I'll be happy to email the formmail script to anyone who can help.

Thanks. A. Grant

A: 

something like this

function formatPhone($number)
{
  $number = str_replace(array('(', ')', '-', ' '), '', $number);
  if (strlen($number) == 10)
  {
    $area = substr($number, 0, 3);
    $part1 = substr($number, 3, 3);
    $part2 = substr($number, 6);

    return "$area-$part1-$part2";
  }
  else
  {
    return false;
  }
}

If the number passed in is 10 digits long, it will return the properly formatted number. Otherwise, it will return FALSE

TenebrousX
+2  A: 
<?php
function formatPhone($number)
 {
    $number = preg_replace('/[^\d]/', '', $number); //Remove anything that is not a number
    if(strlen($number) < 10)
     {
     return false;
     }
    return substr($number, 0, 3) . '-' . substr($number, 3, 3) . '-' . substr($number, 6);
 }


foreach(array('(858)5551212', '(858)555-1212', '8585551212','858-555-1212', '123') as $number)
 {
    $number = formatPhone($number);
    if($number)
      {
          echo $number . "\n";
      }
 }
 ?>

the above returns:

858-555-1212
858-555-1212
858-555-1212
858-555-1212
Unkwntech
Note: TenebrousX's answer is more or less the same, but if we were playing golf I won.
Unkwntech
A: 

Very nice clean code, thanks guys.