Format Phone Number Fields with PHP
Below is a function I wrote to take a phone number entered by a user and convert it into a desired format. The one shown below is 555-555-5555.
View Code PHP
function phn_numb($numb) { if (!is_numeric(substr($numb, 0, 1)) && !is_numeric(substr($numb, 1, 1))) { return $numb; } $chars = array(' ', '(', ')', '-', '.'); $numb = str_replace($chars, "", $numb); if (strlen($numb) > 10) { //you must dial "1" before dialing this number $numb = substr($numb, 0, 1).'-'.substr($numb, 1, 3).'-'.substr($numb, 4, 3).'-'.substr($numb, 7, 4); } else { $numb = substr($numb, 0, 3).'-'.substr($numb, 3, 3).'-'.substr($numb, 5, 4); } return $numb; } |
Therefore to see it in action:
View Code PHP
$phonenumber = 2345678901; echo phn_num($phonenumber); //the resulting echo would be 234-567-8901 |




