Cell: +1 999-(555 0001)
.* zero or more of anything "Cell: +1 "
(\d{3}) three digits "999"
[^\d]{0,7} zero or up to 7 of something not a digit "-("
(\d{3}) three digits "555"
[^\d]{0,7} zero or up to 7 of something not a digit " "
(\d{4}) four digits "0001"
.* zero or more of anything ")"
I think I fixed it. Working for current input files and have following 2 functions to get this done!
函数 format _ phone _ number:
function format_phone_number ( $mynum, $mask ) {
/*********************************************************************/
/* Purpose: Return either masked phone number or false */
/* Masks: Val=1 or xxx xxx xxxx */
/* Val=2 or xxx xxx.xxxx */
/* Val=3 or xxx.xxx.xxxx */
/* Val=4 or (xxx) xxx xxxx */
/* Val=5 or (xxx) xxx.xxxx */
/* Val=6 or (xxx).xxx.xxxx */
/* Val=7 or (xxx) xxx-xxxx */
/* Val=8 or (xxx)-xxx-xxxx */
/*********************************************************************/
$val_num = self::validate_phone_number ( $mynum );
if ( !$val_num && !is_string ( $mynum ) ) {
echo "Number $mynum is not a valid phone number! \n";
return false;
} // end if !$val_num
if ( ( $mask == 1 ) || ( $mask == 'xxx xxx xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'$1 $2 $3'." \n", $mynum);
return $phone;
} // end if $mask == 1
if ( ( $mask == 2 ) || ( $mask == 'xxx xxx.xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'$1 $2.$3'." \n", $mynum);
return $phone;
} // end if $mask == 2
if ( ( $mask == 3 ) || ( $mask == 'xxx.xxx.xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'$1.$2.$3'." \n", $mynum);
return $phone;
} // end if $mask == 3
if ( ( $mask == 4 ) || ( $mask == '(xxx) xxx xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'($1) $2 $3'." \n", $mynum);
return $phone;
} // end if $mask == 4
if ( ( $mask == 5 ) || ( $mask == '(xxx) xxx.xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'($1) $2.$3'." \n", $mynum);
return $phone;
} // end if $mask == 5
if ( ( $mask == 6 ) || ( $mask == '(xxx).xxx.xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'($1).$2.$3'." \n", $mynum);
return $phone;
} // end if $mask == 6
if ( ( $mask == 7 ) || ( $mask == '(xxx) xxx-xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'($1) $2-$3'." \n", $mynum);
return $phone;
} // end if $mask == 7
if ( ( $mask == 8 ) || ( $mask == '(xxx)-xxx-xxxx' ) ) {
$phone = preg_replace('~.*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4}).*~',
'($1)-$2-$3'." \n", $mynum);
return $phone;
} // end if $mask == 8
return false; // Returns false if no conditions meet or input
} // end function format_phone_number
函数 valid_ phone _ number:
function validate_phone_number ( $phone ) {
/*********************************************************************/
/* Purpose: To determine if the passed string is a valid phone */
/* number following one of the establish formatting */
/* styles for phone numbers. This function also breaks */
/* a valid number into it's respective components of: */
/* 3-digit area code, */
/* 3-digit exchange code, */
/* 4-digit subscriber number */
/* and validates the number against 10 digit US NANPA */
/* guidelines. */
/*********************************************************************/
$format_pattern = '/^(?:(?:\((?=\d{3}\)))?(\d{3})(?:(?<=\(\d{3})\))'.
'?[\s.\/-]?)?(\d{3})[\s\.\/-]?(\d{4})\s?(?:(?:(?:'.
'(?:e|x|ex|ext)\.?\:?|extension\:?)\s?)(?=\d+)'.
'(\d+))?$/';
$nanpa_pattern = '/^(?:1)?(?(?!(37|96))[2-9][0-8][0-9](?<!(11)))?'.
'[2-9][0-9]{2}(?<!(11))[0-9]{4}(?<!(555(01([0-9]'.
'[0-9])|1212)))$/';
// Init array of variables to false
$valid = array('format' => false,
'nanpa' => false,
'ext' => false,
'all' => false);
//Check data against the format analyzer
if ( preg_match ( $format_pattern, $phone, $matchset ) ) {
$valid['format'] = true;
}
//If formatted properly, continue
//if($valid['format']) {
if ( !$valid['format'] ) {
return false;
} else {
//Set array of new components
$components = array ( 'ac' => $matchset[1], //area code
'xc' => $matchset[2], //exchange code
'sn' => $matchset[3] //subscriber number
);
// $components = array ( 'ac' => $matchset[1], //area code
// 'xc' => $matchset[2], //exchange code
// 'sn' => $matchset[3], //subscriber number
// 'xn' => $matchset[4] //extension number
// );
//Set array of number variants
$numbers = array ( 'original' => $matchset[0],
'stripped' => substr(preg_replace('[\D]', '', $matchset[0]), 0, 10)
);
//Now let's check the first ten digits against NANPA standards
if(preg_match($nanpa_pattern, $numbers['stripped'])) {
$valid['nanpa'] = true;
}
//If the NANPA guidelines have been met, continue
if ( $valid['nanpa'] ) {
if ( !empty ( $components['xn'] ) ) {
if ( preg_match ( '/^[\d]{1,6}$/', $components['xn'] ) ) {
$valid['ext'] = true;
} // end if if preg_match
} else {
$valid['ext'] = true;
} // end if if !empty
} // end if $valid nanpa
//If the extension number is valid or non-existent, continue
if ( $valid['ext'] ) {
$valid['all'] = true;
} // end if $valid ext
} // end if $valid
return $valid['all'];
} // end functon validate_phone_number
this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.
我知道 OP 要求的格式是123-456-7890,但是,基于 John Dul 的回答,我修改了它以返回括号格式的电话号码,例如(123-R456-7890)。这个只能处理7位和10位数字。
function format_phone_string( $raw_number ) {
// remove everything but numbers
$raw_number = preg_replace( '/\D/', '', $raw_number );
// split each number into an array
$arr_number = str_split($raw_number);
// add a dummy value to the beginning of the array
array_unshift( $arr_number, 'dummy' );
// remove the dummy value so now the array keys start at 1
unset($arr_number[0]);
// get the number of numbers in the number
$num_number = count($arr_number);
// loop through each number backward starting at the end
for ( $x = $num_number; $x >= 0; $x-- ) {
if ( $x === $num_number - 4 ) {
// before the fourth to last number
$phone_number = "-" . $phone_number;
}
else if ( $x === $num_number - 7 && $num_number > 7 ) {
// before the seventh to last number
// and only if the number is more than 7 digits
$phone_number = ") " . $phone_number;
}
else if ( $x === $num_number - 10 ) {
// before the tenth to last number
$phone_number = "(" . $phone_number;
}
// concatenate each number (possibly with modifications) back on
$phone_number = $arr_number[$x] . $phone_number;
}
return $phone_number;
}
$defaultCountry = 'SE'; // Based on the country of the user
$phoneUtil = PhoneNumberUtil::getInstance();
$swissNumberProto = $phoneUtil->parse($phoneNumber, $defaultCountry);
return $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL);
$telephone = New Telephone;
$formattedPhoneNumber = $telephone->toIntegerForm($num)
`
<?php
class Telephone
{
public function toIntegerForm($num) {
/*
* This section takes the number, whatever its format, and purifies it to just digits without any space or other characters
* This ensures that the formatter only has one type of input to deal with
*/
$number = str_replace('+44', '0', $num);
$length = strlen($number);
$digits = '';
$i=0;
while ($i<$length){
$digits .= $this->first( substr($number,$i,1) , $i);
$i++;
}
if (strlen($number)<10) {return '';}
return $this->toTextForm($digits);
}
public function toTextForm($number) {
/*
* This works on the purified number to then format it according to the group code
* Numbers starting 01 and 07 are grouped 5 3 3
* Other numbers are grouped 3 4 4
*
*/
if (substr($number,0,1) == '+') { return $number; }
$group = substr($number,0,2);
switch ($group){
case "02" :
$formattedNumber = $this->teleNum($number, 3, 4); // If number commences '02N' then output will be (02N) NNNN NNNN
break;
default :
$formattedNumber = $this->teleNum($number, 5, 3); // Otherwise the ooutput will be (0NNNN) NNN NNN
}
return $formattedNumber;
}
private function first($digit,$position){
if ($digit == '+' && $position == 0) {return $digit;};
if (!is_numeric($digit)){
return '';
}
if ($position == 0) {
return ($digit == '0' ) ? $digit : '0'.$digit;
} else {
return $digit;
}
}
private function teleNum($number,$a,$b){
/*
* Formats the required output
*/
$c=strlen($number)-($a+$b);
$bit1 = substr($number,0,$a);
$bit2 = substr($number,$a,$b);
$bit3 = substr($number,$a+$b,$c);
return '('.$bit1.') '.$bit2." ".$bit3;
}
}
/**
* Format a provided phone number, with options
*
* @param string $phone The phone number to validate
* @param string $phoneFormat The format we want the number to be in, standard 10 digit no CC by default
* @param string $countryCode The country code, default is 1 for US
* @return string The formatted phone number, or 'INVALID' if the number could not be parsed
* to the given format, or 'EMPTY' if this lead has no phone
*/
function validatePhone(string $phone, string $phoneFormat = "<NPA><NXX><XXXX>", string $countryCode = '1'): string
{
if (empty($phone)) {
return "EMPTY";
}
$phone = preg_replace("/(^\+1)|(^\+)|(^1)/", "", $phone);
if (preg_match("/^.*(?P<NPA>\d{3}).*(?P<NXX>\d{3}).*(?P<XXXX>\d{4})$/", $phone, $parts)) {
$phoneFormat = preg_replace('/<CC>/', $countryCode, $phoneFormat);
$phoneFormat = preg_replace('/<NPA>/', $parts['NPA'], $phoneFormat);
$phoneFormat = preg_replace('/<NXX>/', $parts['NXX'], $phoneFormat);
$phoneFormat = preg_replace('/<XXXX>/', $parts['XXXX'], $phoneFormat);
return $phoneFormat;
} else {
return "INVALID";
}
}
The placeholder-based syntax in the format arguments offers a high degree of control to the developer. Customizing/Maintaining this approach should be less daunting than regex for most developers.