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?!
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:
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)
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.