Formatting Phone Numbers in PHP

Formatting Phone Numbers in PHP

$data = '+11234567890';

if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
return $result;
}

Format Phone Number in PHP

This is what I've used in the past. Not as elegant as a regex I suppose but it can get the job done:

/**
* Formats a phone number
* @param string $phone
*/
static public function formatPhoneNum($phone){
$phone = preg_replace("/[^0-9]*/",'',$phone);
if(strlen($phone) != 10) return(false);
$sArea = substr($phone,0,3);
$sPrefix = substr($phone,3,3);
$sNumber = substr($phone,6,4);
$phone = "(".$sArea.") ".$sPrefix."-".$sNumber;
return($phone);
}

p.s. I didn't write this, just something I grabbed six years ago.

formatting local phone numbers into international (knowing countries)

I previously used this library (without composer) and worked well: https://github.com/davideme/libphonenumber-for-PHP

You only have to include in your php PhoneNumberUtil.php and that file knows what else needs to include.

You can format a number like this:

$swissNumberStr = "044 668 18 00";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
$swissNumberProto = $phoneUtil->parseAndKeepRawInput($swissNumberStr, "CH");
var_dump($swissNumberProto);
} catch (NumberParseException $e) {
echo $e;
}
echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL)

Check demo.php to see more examples on how to use library.

How do you format a 10 digit string into a phone number?

A regex is definitely overkill for this one. If you wanted to take a "phone number" and normalize it to 10 digits, that would be a good use for a regex. To do what you're asking, just do something like:

echo '('.substr($data, 0, 3).') '.substr($data, 3, 3).'-'.substr($data,6);

Since you already know how to divide up your data, you can just use substr or something similar to grab the parts you want. RegEx is useful for matching strings which don't always have a strict format. (Like variable numbers of spaces, variable stuff before or after it, extra dashes, etc). But in your case the input is always strictly formatted 10 digits, nothing else, so you don't need the extra overhead of a RegEx to format it.

how to edit phone number format using php

Here is a one way to do it.

$data = '+19995554444';

if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = '('. $matches[1] . ')' .$matches[2] . '-' . $matches[3];
echo $result;
}

link & Possible duplicate of: Formatting Phone Numbers in PHP



Related Topics



Leave a reply



Submit