Thursday 15 October 2015

Format Phone Numbers In Php

Most web development applications save a 10-digit number in the database without any dashes or parentheses. Hypertext preprocessor (PHP) is a web scripting language that allows the developer to create dynamic pages. The PHP programmer needs to format the phone number before displaying it on the web page, which makes it more easily read by the user. You can use PHP to format a phone number with dashes and parenthesis using the "strlen()" function. This function takes each part of the phone number, parses it, and inserts dashes and parenthesis where appropriate.


Instructions


1. Open the PHP page in any text editor. Navigate to the area of the page where you want to format a phone number and display it to the user.


2. Create a PHP variable and assign it a phone number. The following code saves input from the user and removes any incorrect characters that don't belong in the phone number:


$phone_number = preg_replace("/[^0-9]/", "", $phone_number);


3. Parse the phone number if it's only seven digits. Some users don't use 10-digit dialing in their area, so they have a habit of entering only seven digits. This function detects only seven digits and inserts a dash:


if(strlen($phone_number) == 7)


return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone_number);


4. Insert dashes and parentheses if the phone number is 10 digits. If the phone number is not 7 characters and equals 10 characters, this part of the code is executed:


elseif(strlen($phone_number) == 10)


return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone_number);


5. Return the phone number without any formatting if it is not any of the standard lengths. This method is used as a default to print output to the user. The final code is below:


else


return $phone_number;

Tags: phone number, format phone number, only seven, only seven digits, seven digits, dashes parentheses