views:

124

answers:

2

Here's my Codeigniter function:

function edit_phone($phone)
{
            if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $phone))
            {
             return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone); 
            }
            else
            {
            $this->CI->validation->set_message('phone', "This must be a 10-digit USA phone number.");
                    return FALSE;       
            }
}

This validates/checks the input alright, but doesn't reformat it in the db.

Validation is great! But why isn't this returning a standard phone number?!

+2  A: 

Could you please give us example data, that you tried to fill in?

I used the following code:

$phone = "1234567890";
echo preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone);

and got:

123-456-7890

which is absolutely correct, as far as I can tell.

FlorianH
I believe Michael is correct. Could you please tell me how I would grab the return?
Kevin Brown
`$phone_number = edit_phone("1234567890");` the return value is now in `$phone_number`
Carson Myers
+3  A: 

I think the problem is that it will ONLY work with a number in the format 1234567890, but based on the regular expression in the preg_match() call, Kevin is also looking to accommodate numbers like:

  • (123)4567890
  • (123) 456 7890
  • 123-456-7890

If so, the regex in the preg_replace() needs to be something like...

preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', "$1-$2-$3", $phone)

Greg