18 Aug 2009 Ferado

Using PHP to format phone numbers

PHP is great. It complements JavaScript wonderfully. You may have already formatted the phone number on the front end, but what about on the backend? There comes a time when you need to use php to format a phone number. I use this function in my projects all the time.

PHP Format Phone Number Function

[cc lang=”php”]

function format_phone($country, $phone) {
$function = ‘format_phone_’ . $country;
if(function_exists($function)) {
return $function($phone);
}
return $phone;
}

function format_phone_us($phone) {
// note: making sure we have something
if(!isset($phone{3})) { return ”; }
// note: strip out everything but numbers
$phone = preg_replace(“/[^0-9]/”, “”, $phone);
$length = strlen($phone);
switch($length) {
case 7:
return preg_replace(“/([0-9]{3})([0-9]{4})/”, “$1-$2”, $phone);
break;
case 10:
return preg_replace(“/([0-9]{3})([0-9]{3})([0-9]{4})/”, “($1) $2-$3”, $phone);
break;
case 11:
return preg_replace(“/([0-9{1})([0-9]{3})([0-9]{3})([0-9]{4})/”, “$1($2) $3-$4”, $phone);
break;
default:
return $phone;
break;
}
}

// usage
$phone = ‘111 111 1111’;
$phone = format_phone(‘us’, $phone);
echo $phone;

[/cc]

Continue reading “Using PHP to format phone numbers” »

18 Apr 2009 Ferado

Simple copyright year function

I still see on a lot of sites the copyright date being outdated. Shoot, it was even outdated on mine. How embarrassing. Easy fix though. Something I do at work all the time, but since I’m not getting paid for this site, it wasn’t done.

Now, let’s forget the past and move onto the future.

The solution (in PHP):

[cc lang=”php”]
function copyright_year($year = ‘2009’, $sep = ‘-‘) {
$current_year = date(‘Y’);
return ($year == $current_year) ? $year : $year . $sep . $current_year;
}
[/cc]

OR, for those that need more lines (I do too. I like to be able to READ my code):

[cc lang=”php”]
function copyright_year($year = ‘2009’, $sep = ‘-‘) {

$current_year = date(‘Y’);

// compare year that is passed in with current year
if($year == $current_year) {
return $year;
}

// I hate writing the word “else”
return $year . $sep . $current_year;

}
[/cc]

I’ve also made it easy for you to download the source code, just in case you like things REALLY simple! I do, don’t be shy.

DOWNLOAD SOURCE CODE