Skip to content

Instantly share code, notes, and snippets.

@aliharis
Created April 13, 2014 07:42
Show Gist options
  • Save aliharis/10573509 to your computer and use it in GitHub Desktop.
Save aliharis/10573509 to your computer and use it in GitHub Desktop.
Format Telephone Number with PHP
<?php
function formatTelephoneNo($phone_number, $country_code = false)
{
$cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
if ($country_code) {
preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
return "({$matches[1]}) {$matches[2]} {$matches[3]}";
}
preg_match('/(\d{3})(\d{4})/', $cleaned, $matches);
return "{$matches[1]} {$matches[2]}";
}
@aliharis
Copy link
Author

Usage: With country code

echo formatTelephoneNo("+9603303033", true);
Result: (960) 330 3033

Usage: Without country code

echo formatTelephoneNo("3303033");
Result: 330 3033

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment