Cleaning up a Phone Number Entry with PHP

0

July 4, 2012 by Al

When people type phone numbers into forms they might do so in any number of ways, such as

(502) 896-9876
502-896-9876
5028969876
502.896.6976

and so on.

These different formats can be a problem if the phone number is stored in a database for later retrieval on a different page or pages. The smart thing to do is to standardize how you store a phone number in the first place so that when it is retrieved it can be reformatted easily into whatever format you would like. One convenient thing to do is to strip out all the ‘non-numbers’ in the phone number and just store the ten digits.

Assume one of the fields on your html form is “phone”. When the user submits the form to your processing script, you can include code such as the following:

<?php

//connect to database using your standard 'connect' script
include_once "connection-parameters.php";

//clean the data to guard against injection attacks
$ph = mysql_real_escape_string($_POST['phone']);

//strip out any unwanted characters in the phone number
$ph = preg_replace('/[^0-9]/','',$ph);

//enter data into database
$sql = "insert into tablename (phone) values ('$ph');

The data will be entered into the database in the form “5028969865”.

When you retrieve if from the database you can format however you like, for example:

$sql = "select phone from tablename";
$res = mysql_query($sql);
while($row=mysql_fetch_array($res)) {
  extract($row);
  $areacode   = substr($phone,0,3);
  $exchange   = substr($phone,3,3);
  $number     = substr($phone,-4);
  $phone_num  = "(" . $areacode . ") "; 
  $phone_num .= $exchange;
  $phone_num .= "-" . $number;
  echo $phone_num;
}

…and this will give you ‘(502) 896-9865’


0 comments

Sorry, comments are closed.