Moodle PHP Documentation 5.0
Moodle 5.0.1+ (Build: 20250711) (61af040cd5f)
libphonenumber\PhoneNumberUtil Class Reference

Public Member Functions

 canBeInternationallyDialled (PhoneNumber $number)
 Returns true if the number can be dialled from outside the region, or unknown.
 
 chooseFormattingPatternForNumber (array $availableFormats, string $nationalNumber)
 
 format (PhoneNumber $number, int $numberFormat)
 Formats a phone number in the specified format using default rules.
 
 formatByPattern (PhoneNumber $number, int $numberFormat, array $userDefinedFormats)
 Formats a phone number in the specified format using client-defined formatting rules.
 
 formatInOriginalFormat (PhoneNumber $number, string $regionCallingFrom)
 Formats a phone number using the original phone number format (e.g.
 
 formatNationalNumberWithCarrierCode (PhoneNumber $number, string $carrierCode)
 Formats a phone number in national format for dialing using the carrier as specified in the carrierCode.
 
 formatNationalNumberWithPreferredCarrierCode (PhoneNumber $number, string $fallbackCarrierCode)
 Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in.
 
 formatNsnUsingPattern (string $nationalNumber, NumberFormat $formattingPattern, int $numberFormat, ?string $carrierCode=null)
 Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.
 
 formatNumberForMobileDialing (PhoneNumber $number, string $regionCallingFrom, bool $withFormatting)
 Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region.
 
 formatOutOfCountryCallingNumber (PhoneNumber $number, string $regionCallingFrom)
 Formats a phone number for out-of-country dialing purposes.
 
 formatOutOfCountryKeepingAlphaChars (PhoneNumber $number, string $regionCallingFrom)
 Formats a phone number for out-of-country dialing purposes.
 
 getCountryCodeForRegion (?string $regionCode)
 Returns the country calling code for a specific region.
 
 getExampleNumber (string $regionCode)
 Gets a valid number for the specified region.
 
 getExampleNumberForNonGeoEntity (int $countryCallingCode)
 Gets a valid number for the specified country calling code for a non-geographical entity.
 
 getExampleNumberForType (string|int $regionCodeOrType, ?int $type=null)
 Gets a valid number for the specified region and number type.
 
 getInvalidExampleNumber (string $regionCode)
 Gets an invalid number for the specified region.
 
 getLengthOfGeographicalAreaCode (PhoneNumber $number)
 Gets the length of the geographical area code from the nationalNumber field of the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number.
 
 getLengthOfNationalDestinationCode (PhoneNumber $number)
 Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number.
 
 getMetadataForNonGeographicalRegion (int $countryCallingCode)
 
 getMetadataForRegion (?string $regionCode)
 Returns the metadata for the given region code or null if the region code is invalid or unknown.
 
 getNationalSignificantNumber (PhoneNumber $number)
 Gets the national significant number of the phone number.
 
 getNddPrefixForRegion (string $regionCode, bool $stripNonDigits)
 Returns the national dialling prefix for a specific region.
 
 getNumberType (PhoneNumber $number)
 Gets the type of a valid phone number.
 
 getRegionCodeForCountryCode (int $countryCallingCode)
 Returns the region code that matches the specific country calling code.
 
 getRegionCodeForNumber (PhoneNumber $number)
 Returns the region where a phone number is from.
 
 getRegionCodesForCountryCode (int $countryCallingCode)
 Returns a list with the region codes that match the specific country calling code.
 
 getSupportedCallingCodes ()
 Returns all country calling codes the library has metadata for, covering both non-geographical entities (global network calling codes) and those used for geographical entities.
 
 getSupportedGlobalNetworkCallingCodes ()
 Returns all global network calling codes the library has metadata for.
 
 getSupportedRegions ()
 Returns all regions the library has metadata for.
 
 getSupportedTypesForNonGeoEntity (int $countryCallingCode)
 Returns the types for a country-code belonging to a non-geographical entity which the library has metadata for.
 
 getSupportedTypesForRegion (string $regionCode)
 Returns the types for a given region which the library has metadata for.
 
 isAlphaNumber (string $number)
 Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT.
 
 isMobileNumberPortableRegion (string $regionCode)
 Returns true if the supplied region supports mobile number portability.
 
 isNANPACountry (string $regionCode)
 Checks if this is a region under the North American Numbering Plan Administration (NANPA).
 
 isNumberGeographical (PhoneNumber|int $phoneNumberObjOrType, ?int $countryCallingCode=null)
 isNumberGeographical(PhoneNumber)
 
 isNumberMatch (PhoneNumber|string $firstNumberIn, PhoneNumber|string $secondNumberIn)
 Takes two phone numbers and compares them for equality.
 
 isNumberMatchingDesc (string $nationalNumber, PhoneNumberDesc $numberDesc)
 
 isPossibleNumber (PhoneNumber|string $number, ?string $regionDialingFrom=null)
 Check whether a phone number is a possible number given a number in the form of a string, and the region where the number could be dialed from.
 
 isPossibleNumberForType (PhoneNumber $number, int $type)
 Convenience wrapper around isPossibleNumberForTypeWithReason.
 
 isPossibleNumberForTypeWithReason (PhoneNumber $number, int $type)
 Check whether a phone number is a possible number of a particular type.
 
 isPossibleNumberWithReason (PhoneNumber $number)
 Check whether a phone number is a possible number.
 
 isValidNumber (PhoneNumber $number)
 Tests whether a phone number matches a valid pattern.
 
 isValidNumberForRegion (PhoneNumber $number, string $regionCode)
 Tests whether a phone number is valid for a certain region.
 
 maybeExtractCountryCode (string $number, ?PhoneMetadata $defaultRegionMetadata, string &$nationalNumber, bool $keepRawInput, PhoneNumber $phoneNumber)
 Tries to extract a country calling code from a number.
 
 maybeStripInternationalPrefixAndNormalize (string &$number, string $possibleIddPrefix)
 Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes the resulting number, and indicates if an international prefix was present.
 
 maybeStripNationalPrefixAndCarrierCode (string &$number, PhoneMetadata $metadata, ?string &$carrierCode)
 Strips any national prefix (such as 0, 1) present in the number provided.
 
 parse (string $numberToParse, ?string $defaultRegion=null, ?PhoneNumber $phoneNumber=null, bool $keepRawInput=false)
 Parses a string and returns it as a phone number in proto buffer format.
 
 parseAndKeepRawInput (string $numberToParse, ?string $defaultRegion, ?PhoneNumber $phoneNumber=null)
 Parses a string and returns it in proto buffer format.
 
 truncateTooLongNumber (PhoneNumber $number)
 Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version.
 

Static Public Member Functions

static convertAlphaCharactersInNumber (string $number)
 Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.
 
static extractPossibleNumber (string $number)
 Attempts to extract a possible number from the string passed in.
 
static formattingRuleHasFirstGroupOnly (string $nationalPrefixFormattingRule)
 Helper function to check if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix.
 
static getCountryMobileToken (int $countryCallingCode)
 Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string.
 
static getInstance (string $baseFileLocation=self::META_DATA_FILE_PREFIX, ?array $countryCallingCodeToRegionCodeMap=null, ?MetadataLoaderInterface $metadataLoader=null, ?MetadataSourceInterface $metadataSource=null)
 Gets a PhoneNumberUtil instance to carry out international phone number formatting, parsing or validation.
 
static isViablePhoneNumber (string $number)
 Checks to see if the string of characters could possibly be a phone number at all.
 
static normalize (string $number)
 Normalizes a string of characters representing a phone number.
 
static normalizeDiallableCharsOnly (string $number)
 Normalizes a string of characters representing a phone number.
 
static normalizeDigits (string $number, bool $keepNonDigits)
 
static normalizeDigitsOnly (string $number)
 Normalizes a string of characters representing a phone number.
 
static resetInstance ()
 Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
 
static setItalianLeadingZerosForPhoneNumber (string $nationalNumber, PhoneNumber $phoneNumber)
 A helper function to set the values related to leading zeros in a PhoneNumber.
 

Public Attributes

const META_DATA_FILE_PREFIX = __DIR__ . '/data/PhoneNumberMetadata'
 
const PLUS_CHARS_PATTERN = '[' . self::PLUS_CHARS . ']+'
 
const REGION_CODE_FOR_NON_GEO_ENTITY = '001'
 

Protected Member Functions

 __construct (MetadataSourceInterface $metadataSource, array $countryCallingCodeToRegionCodeMap)
 This class implements a singleton, so the only constructor is protected.
 
 buildNationalNumberForParsing (string $numberToParse, string &$nationalNumber)
 Converts numberToParse to a form that we can parse and write it to nationalNumber if it is written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
 
 checkRegionForParsing (?string $numberToParse, ?string $defaultRegion)
 Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number.
 
 extractCountryCode (string $fullNumber, string &$nationalNumber)
 Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber.
 
 extractPhoneContext (string $numberToExtractFrom, int|false $indexOfPhoneContext)
 Extracts the value of the phone-context parameter of numberToExtractFrom where the index of ";phone-context=" is the parameter indexOfPhoneContext, following the syntax defined in RFC3966.
 
 formatNsn (string $number, PhoneMetadata $metadata, int $numberFormat, ?string $carrierCode=null)
 Note in some regions, the national number can be written in two completely different ways depending on whether it forms part of the NATIONAL format or INTERNATIONAL format.
 
 getCountryCodeForValidRegion (string $regionCode)
 Returns the country calling code for a specific region.
 
 getMetadataForRegionOrCallingCode (int $countryCallingCode, string $regionCode)
 
 getNumberDescByType (PhoneMetadata $metadata, int $type)
 
 getNumberTypeHelper (string $nationalNumber, PhoneMetadata $metadata)
 Returns the type of number passed in i.e Toll free, premium.
 
 getRegionCodeForNumberFromRegionList (PhoneNumber $number, array $regionCodes)
 Returns the region code for a number from the list of region codes passing in.
 
 hasFormattingPatternForNumber (PhoneNumber $number)
 
 hasValidCountryCallingCode (int $countryCallingCode)
 Helper function to check the country calling code is valid.
 
 init ()
 
 isNationalNumberSuffixOfTheOther (PhoneNumber $firstNumber, PhoneNumber $secondNumber)
 Returns true when one national number is the suffix of the other or both are the same.
 
 isPhoneContextValid (?string $phoneContext)
 Returns whether the value of phoneContext follows the syntax defined in RFC3966.
 
 isValidRegionCode (?string $regionCode)
 Helper function to check region code is not unknown or null.
 
 maybeAppendFormattedExtension (PhoneNumber $number, ?PhoneMetadata $metadata, int $numberFormat, string &$formattedNumber)
 Appends the formatted extension of a phone number to formattedNumber, if the phone number had an extension specified.
 
 maybeStripExtension (string &$number)
 Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
 
 parseHelper (string $numberToParse, ?string $defaultRegion, bool $keepRawInput, bool $checkRegion, PhoneNumber $phoneNumber)
 Parses a string and fills up the phoneNumber.
 
 parsePrefixAsIdd (string $iddPattern, string &$number)
 Strips the IDD from the start of the number if present.
 
 prefixNumberWithCountryCallingCode (int $countryCallingCode, int $numberFormat, string &$formattedNumber)
 A helper function that is used by format and formatByPattern.
 
 rawInputContainsNationalPrefix (string $rawInput, string $nationalPrefix, string $regionCode)
 Check if rawInput, which is assumed to be in the national format, has a national prefix.
 
 testNumberLength (string $number, PhoneMetadata $metadata, int $type=PhoneNumberType::UNKNOWN)
 Helper method to check a number against possible lengths for this number type, and determine whether it matches, or is too short or too long.
 

Static Protected Member Functions

static copyCoreFieldsOnly (PhoneNumber $phoneNumberIn)
 Returns a new phone number containing only the fields needed to uniquely identify a phone number, rather than any fields that capture the context in which the phone number was created.
 
static createExtnPattern (bool $forParsing)
 Helper initialiser method to create the regular-expression pattern to match extensions.
 
static descHasData (PhoneNumberDesc $desc)
 Returns true if there is any data set for a particular PhoneNumberDesc.
 
static descHasPossibleNumberData (PhoneNumberDesc $desc)
 Returns true if there is any possible number data set for a particular PhoneNumberDesc.
 
static extnDigits (int $maxLength)
 Helper method for constructing regular expressions for parsing.
 
static getValidPhoneNumberPattern ()
 We append optionally the extension pattern to the end here, as a valid phone number may have an extension prefix appended, followed by 1 or more digits.
 
static initExtnPattern ()
 
static initExtnPatterns ()
 
static initRFC3966Patterns ()
 
static initValidPhoneNumberPatterns ()
 
static normalizeHelper (string $number, array $normalizationReplacements, bool $removeNonMatches)
 Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein, and stripping all other characters if removeNonMatches is true.
 

Protected Attributes

array< int, string[]> array $countryCallingCodeToRegionCodeMap = []
 A mapping from a country calling code to the region codes which denote the region represented by that country calling code.
 
int[] array $countryCodesForNonGeographicalRegion = []
 The set of county calling codes that map to the non-geo entity region ("001").
 
MatcherAPIInterface $matcherAPI
 
MetadataSourceInterface $metadataSource
 
string[] array $nanpaRegions = []
 The set of regions that share country calling code 1.
 
string[] array $supportedRegions = []
 The set of regions the library supports.
 
const ALPHA_MAPPINGS
 Only upper-case variants of alpha characters are stored.
 
const ALPHA_PHONE_MAPPINGS = self::ALPHA_MAPPINGS + self::ASCII_DIGIT_MAPPINGS
 For performance reasons, amalgamate both into one map.
 
const ASCII_DIGIT_MAPPINGS
 Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
 
const CAPTURING_DIGIT_PATTERN = '(' . self::DIGITS . ')'
 
const CC_STRING = '$CC'
 
const COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES
 Set of country codes that doesn't have national prefix, but it has area codes.
 
const DEFAULT_EXTN_PREFIX = ' ext. '
 
const DIALLABLE_CHAR_MAPPINGS
 
const DIGITS = '\\p{Nd}'
 
const FG_STRING = '$FG'
 
const FIRST_GROUP_ONLY_PREFIX_PATTERN = '\\‍(?\\$1\\‍)?'
 
const FIRST_GROUP_PATTERN = '(\$\\d)'
 
const GEO_MOBILE_COUNTRIES
 Set of country calling codes that have geographically assigned mobile numbers.
 
const GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES
 Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES below) which are not based on area codes.
 
const MAX_INPUT_STRING_LENGTH = 250
 
const MAX_LENGTH_COUNTRY_CODE = 3
 
const MAX_LENGTH_FOR_NSN = 17
 
const MIN_LENGTH_FOR_NSN = 2
 
const MOBILE_TOKEN_MAPPINGS
 Map of country calling codes that use a mobile token before the area code.
 
const NANPA_COUNTRY_CODE = 1
 
const NON_DIGITS_PATTERN = '(\\D+)'
 
const NP_STRING = '$NP'
 
array< string, int > const NUMERIC_CHARACTERS
 
const PLUS_CHARS = '++'
 
const PLUS_SIGN = '+'
 
const REGEX_FLAGS = 'ui'
 Flags to use when compiling regular expressions for phone numbers.
 
const RFC3966_EXTN_PREFIX = ';ext='
 
const RFC3966_ISDN_SUBADDRESS = ';isub='
 
const RFC3966_PHONE_CONTEXT = ';phone-context='
 
const RFC3966_PREFIX = 'tel:'
 
const SECOND_NUMBER_START_PATTERN = '[\\\\/] *x'
 
const SEPARATOR_PATTERN = '[' . self::VALID_PUNCTUATION . ']+'
 
const SINGLE_INTERNATIONAL_PREFIX = "[\\d]+(?:[~\xE2\x81\x93\xE2\x88\xBC\xEF\xBD\x9E][\\d]+)?"
 
const STAR_SIGN = '*'
 
const UNKNOWN_REGION = 'ZZ'
 
const UNWANTED_END_CHAR_PATTERN = '[^' . self::DIGITS . self::VALID_ALPHA . '#]+$'
 
const VALID_ALPHA = 'A-Za-z'
 
const VALID_ALPHA_PHONE_PATTERN = '(?:.*?[A-Za-z]){3}.*'
 
const VALID_PUNCTUATION = "-x\xE2\x80\x90-\xE2\x80\x95\xE2\x88\x92\xE3\x83\xBC\xEF\xBC\x8D-\xEF\xBC\x8F xC2\xA0\xC2\xAD\xE2\x80\x8B\xE2\x81\xA0\xE3\x80\x80()\xEF\xBC\x88\xEF\xBC\x89\xEF\xBC\xBB\xEF\xBC\xBD.\\[\\]/~\xE2\x81\x93\xE2\x88\xBC"
 
const VALID_START_CHAR_PATTERN = '[' . self::PLUS_CHARS . self::DIGITS . ']'
 

Static Protected Attributes

static array< string, string > array $ALL_PLUS_NUMBER_GROUPING_SYMBOLS
 Separate map of all symbols that we wish to retain when formatting alpha numbers.
 
static string $ALPHANUM
 
static string $EXTN_PATTERN
 
static string $EXTN_PATTERNS_FOR_MATCHING
 
static string $EXTN_PATTERNS_FOR_PARSING
 Regexp of all possible ways to write extensions, for use when parsing.
 
static PhoneNumberUtil $instance = null
 
static string $MIN_LENGTH_PHONE_NUMBER_PATTERN
 
static string $RFC3966_DOMAINLABEL
 
static string $RFC3966_DOMAINNAME
 
static string $RFC3966_GLOBAL_NUMBER_DIGITS
 
static string $RFC3966_PHONE_DIGIT
 
static string $RFC3966_TOPLABEL
 
static string $RFC3966_VISUAL_SEPARATOR = '[\\-\\.\\‍(\\‍)]?'
 
static string $VALID_PHONE_NUMBER
 Regular expression of viable phone numbers.
 
static string $VALID_PHONE_NUMBER_PATTERN
 

Constructor & Destructor Documentation

◆ __construct()

libphonenumber\PhoneNumberUtil::__construct ( MetadataSourceInterface $metadataSource,
array $countryCallingCodeToRegionCodeMap )
protected

This class implements a singleton, so the only constructor is protected.

Parameters
array<int,string[]>$countryCallingCodeToRegionCodeMap

Member Function Documentation

◆ buildNationalNumberForParsing()

libphonenumber\PhoneNumberUtil::buildNationalNumberForParsing ( string $numberToParse,
string & $nationalNumber )
protected

Converts numberToParse to a form that we can parse and write it to nationalNumber if it is written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.

Exceptions
NumberParseException

◆ canBeInternationallyDialled()

libphonenumber\PhoneNumberUtil::canBeInternationallyDialled ( PhoneNumber $number)

Returns true if the number can be dialled from outside the region, or unknown.

If the number can only be dialled from within the region, returns false. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country).

Parameters
PhoneNumber$numberthe phone-number for which we want to know whether it is diallable from outside the region

◆ checkRegionForParsing()

libphonenumber\PhoneNumberUtil::checkRegionForParsing ( ?string $numberToParse,
?string $defaultRegion )
protected

Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number.

Returns false if it cannot use the region provided and the region cannot be inferred.

◆ chooseFormattingPatternForNumber()

libphonenumber\PhoneNumberUtil::chooseFormattingPatternForNumber ( array $availableFormats,
string $nationalNumber )
Parameters
NumberFormat[]$availableFormats

◆ copyCoreFieldsOnly()

static libphonenumber\PhoneNumberUtil::copyCoreFieldsOnly ( PhoneNumber $phoneNumberIn)
staticprotected

Returns a new phone number containing only the fields needed to uniquely identify a phone number, rather than any fields that capture the context in which the phone number was created.

These fields correspond to those set in parse() rather than parseAndKeepRawInput()

◆ createExtnPattern()

static libphonenumber\PhoneNumberUtil::createExtnPattern ( bool $forParsing)
staticprotected

Helper initialiser method to create the regular-expression pattern to match extensions.

Note that there are currently six capturing groups for the extension itself. If this number is changed, MaybeStripExtension needs to be updated.

◆ extnDigits()

static libphonenumber\PhoneNumberUtil::extnDigits ( int $maxLength)
staticprotected

Helper method for constructing regular expressions for parsing.

Creates an expression that captures up to maxLength digits.

◆ extractCountryCode()

libphonenumber\PhoneNumberUtil::extractCountryCode ( string $fullNumber,
string & $nationalNumber )
protected

Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber.

It assumes that the leading plus sign or IDD has already been removed. Returns 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber unmodified.

◆ extractPhoneContext()

libphonenumber\PhoneNumberUtil::extractPhoneContext ( string $numberToExtractFrom,
int|false $indexOfPhoneContext )
protected

Extracts the value of the phone-context parameter of numberToExtractFrom where the index of ";phone-context=" is the parameter indexOfPhoneContext, following the syntax defined in RFC3966.

Return values
string|nullthe extracted string (possibly empty), or null if no phone-context parameter is found.

◆ extractPossibleNumber()

static libphonenumber\PhoneNumberUtil::extractPossibleNumber ( string $number)
static

Attempts to extract a possible number from the string passed in.

This currently strips all leading characters that cannot be used to start a phone number. Characters that can be used to start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters are found in the number passed in, an empty string is returned. This function also attempts to strip off any alternative extensions or endings if two or more are present, such as in the case of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first number is parsed correctly.

Parameters
string$numberthe string that might contain a phone number
Return values
stringthe number, stripped of any non-phone-number prefix (such as "Tel:") or an empty string if no character used to start phone numbers (such as + or any digit) is found in the number

◆ format()

libphonenumber\PhoneNumberUtil::format ( PhoneNumber $number,
int $numberFormat )

Formats a phone number in the specified format using default rules.

Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied.

Parameters
PhoneNumber$numberthe phone number to be formatted
int$numberFormatthe PhoneNumberFormat the phone number should be formatted into
Return values
stringthe formatted phone number

◆ formatByPattern()

libphonenumber\PhoneNumberUtil::formatByPattern ( PhoneNumber $number,
int $numberFormat,
array $userDefinedFormats )

Formats a phone number in the specified format using client-defined formatting rules.

Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied.

Parameters
PhoneNumber$numberthe phone number to be formatted
int$numberFormatthe format the phone number should be formatted into
NumberFormat[]$userDefinedFormatsformatting rules specified by clients
Return values
Stringthe formatted phone number

◆ formatInOriginalFormat()

libphonenumber\PhoneNumberUtil::formatInOriginalFormat ( PhoneNumber $number,
string $regionCallingFrom )

Formats a phone number using the original phone number format (e.g.

INTERNATIONAL or NATIONAL) that the number is parsed from, provided that the number has been parsed with parseAndKeepRawInput. Otherwise the number will be formatted in NATIONAL format.

The original format is embedded in the country_code_source field of the PhoneNumber object passed in, which is only set when parsing keeps the raw input. When we don't have a formatting pattern for the number, the method falls back to returning the raw input.

Note this method guarantees no digit will be inserted, removed or modified as a result of formatting.

Parameters
PhoneNumber$numberthe phone number that needs to be formatted in its original number format
string$regionCallingFromthe region whose IDD needs to be prefixed if the original number has one
Return values
stringthe formatted phone number in its original number format

◆ formatNationalNumberWithCarrierCode()

libphonenumber\PhoneNumberUtil::formatNationalNumberWithCarrierCode ( PhoneNumber $number,
string $carrierCode )

Formats a phone number in national format for dialing using the carrier as specified in the carrierCode.

The carrierCode will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrierCode contains an empty string, returns the number in national format without any carrier code.

Parameters
PhoneNumber$numberthe phone number to be formatted
string$carrierCodethe carrier selection code to be used
Return values
stringthe formatted phone number in national format for dialing using the carrier as specified in the carrierCode

◆ formatNationalNumberWithPreferredCarrierCode()

libphonenumber\PhoneNumberUtil::formatNationalNumberWithPreferredCarrierCode ( PhoneNumber $number,
string $fallbackCarrierCode )

Formats a phone number in national format for dialing using the carrier as specified in the preferredDomesticCarrierCode field of the PhoneNumber object passed in.

If that is missing, use the fallbackCarrierCode passed in instead. If there is no preferredDomesticCarrierCode, and the fallbackCarrierCode contains an empty string, return the number in national format without any carrier code.

Use formatNationalNumberWithCarrierCode instead if the carrier code passed in should take precedence over the number's preferredDomesticCarrierCode when formatting.

Parameters
PhoneNumber$numberthe phone number to be formatted
string$fallbackCarrierCodethe carrier selection code to be used, if none is found in the phone number itself
Return values
stringthe formatted phone number in national format for dialing using the number's preferredDomesticCarrierCode, or the fallbackCarrierCode passed in if none is found

◆ formatNsn()

libphonenumber\PhoneNumberUtil::formatNsn ( string $number,
PhoneMetadata $metadata,
int $numberFormat,
?string $carrierCode = null )
protected

Note in some regions, the national number can be written in two completely different ways depending on whether it forms part of the NATIONAL format or INTERNATIONAL format.

The numberFormat parameter here is used to specify which format to use for those cases. If a carrierCode is specified, this will be inserted into the formatted string to replace $CC.

Parameters
int$numberFormatPhoneNumberFormat

◆ formatNsnUsingPattern()

libphonenumber\PhoneNumberUtil::formatNsnUsingPattern ( string $nationalNumber,
NumberFormat $formattingPattern,
int $numberFormat,
?string $carrierCode = null )

Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.

Parameters
int$numberFormatPhoneNumberFormat

◆ formatNumberForMobileDialing()

libphonenumber\PhoneNumberUtil::formatNumberForMobileDialing ( PhoneNumber $number,
string $regionCallingFrom,
bool $withFormatting )

Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region.

If the number cannot be reached from the region (e.g. some countries block toll-free numbers from being called outside of the country), the method returns an empty string.

Parameters
PhoneNumber$numberthe phone number to be formatted
string$regionCallingFromthe region where the call is being placed
boolean$withFormattingwhether the number should be returned with formatting symbols, such as spaces and dashes.
Return values
stringthe formatted phone number

◆ formatOutOfCountryCallingNumber()

libphonenumber\PhoneNumberUtil::formatOutOfCountryCallingNumber ( PhoneNumber $number,
string $regionCallingFrom )

Formats a phone number for out-of-country dialing purposes.

If no regionCallingFrom is supplied, we format the number in its INTERNATIONAL format. If the country calling code is the same as that of the region where the number is from, then NATIONAL formatting will be applied.

If the number itself has a country calling code of zero or an otherwise invalid country calling code, then we return the number with no formatting applied.

Note this function takes care of the case for calling inside of NANPA and between Russia and Kazakhstan (who share the same country calling code). In those cases, no international prefix is used. For regions which have multiple international prefixes, the number in its INTERNATIONAL format will be returned instead.

Parameters
PhoneNumber$numberthe phone number to be formatted
string$regionCallingFromthe region where the call is being placed
Return values
stringthe formatted phone number

◆ formatOutOfCountryKeepingAlphaChars()

libphonenumber\PhoneNumberUtil::formatOutOfCountryKeepingAlphaChars ( PhoneNumber $number,
string $regionCallingFrom )

Formats a phone number for out-of-country dialing purposes.

Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping information, as specified by characters such as "-" and " ", will be retained.

Caveats:

  • This will not produce good results if the country calling code is both present in the raw input and is the start of the national number. This is not a problem in the regions which typically use alpha numbers.
  • This will also not produce good results if the raw input has any grouping information within the first three digits of the national number, and if the function needs to strip preceding digits/words in the raw input before these digits. Normally people group the first three digits together so this is not a huge problem - and will be fixed if it proves to be so.
Parameters
PhoneNumber$numberthe phone number that needs to be formatted
string$regionCallingFromthe region where the call is being placed
Return values
stringthe formatted phone number

◆ getCountryCodeForRegion()

libphonenumber\PhoneNumberUtil::getCountryCodeForRegion ( ?string $regionCode)

Returns the country calling code for a specific region.

For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid.

Parameters
string | null$regionCodethe region that we want to get the country calling code for
Return values
intthe country calling code for the region denoted by regionCode

◆ getCountryCodeForValidRegion()

libphonenumber\PhoneNumberUtil::getCountryCodeForValidRegion ( string $regionCode)
protected

Returns the country calling code for a specific region.

For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid.

Parameters
string$regionCodethe region that we want to get the country calling code for
Return values
intthe country calling code for the region denoted by regionCode
Exceptions
InvalidArgumentExceptionif the region is invalid

◆ getCountryMobileToken()

static libphonenumber\PhoneNumberUtil::getCountryMobileToken ( int $countryCallingCode)
static

Returns the mobile token for the provided country calling code if it has one, otherwise returns an empty string.

A mobile token is a number inserted before the area code when dialing a mobile number from that country from abroad.

Parameters
int$countryCallingCodethe country calling code for which we want the mobile token
Return values
stringthe mobile token, as a string, for the given country calling code

◆ getExampleNumber()

libphonenumber\PhoneNumberUtil::getExampleNumber ( string $regionCode)

Gets a valid number for the specified region.

Parameters
string$regionCodethe region for which an example number is needed
Return values
PhoneNumber|nulla valid fixed-line number for the specified region. Returns null when the metadata does not contain such information, or the region 001 is passed in. For 001 (representing non-geographical numbers), call getExampleNumberForNonGeoEntity instead.

◆ getExampleNumberForNonGeoEntity()

libphonenumber\PhoneNumberUtil::getExampleNumberForNonGeoEntity ( int $countryCallingCode)

Gets a valid number for the specified country calling code for a non-geographical entity.

Parameters
int$countryCallingCodethe country calling code for a non-geographical entity
Return values
PhoneNumber|nulla valid number for the non-geographical entity. Returns null when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.

◆ getExampleNumberForType()

libphonenumber\PhoneNumberUtil::getExampleNumberForType ( string|int $regionCodeOrType,
?int $type = null )

Gets a valid number for the specified region and number type.

Parameters
string | int$regionCodeOrTypethe region for which an example number is needed
int$typethe PhoneNumberType of number that is needed
Return values
PhoneNumber|nulla valid number for the specified region and type. Returns null when the metadata does not contain such information or if an invalid region or region 001 was entered. For 001 (representing non-geographical numbers), call getExampleNumberForNonGeoEntity instead.

If $regionCodeOrType is the only parameter supplied, then a valid number for the specified number type will be returned that may belong to any country.

◆ getInstance()

static libphonenumber\PhoneNumberUtil::getInstance ( string $baseFileLocation = self::META_DATA_FILE_PREFIX,
?array $countryCallingCodeToRegionCodeMap = null,
?MetadataLoaderInterface $metadataLoader = null,
?MetadataSourceInterface $metadataSource = null )
static

Gets a PhoneNumberUtil instance to carry out international phone number formatting, parsing or validation.

The instance is loaded with phone number metadata for a number of most commonly used regions.

The PhoneNumberUtil is implemented as a singleton. Therefore, calling getInstance multiple times will only result in one instance being created.

Parameters
array<int,array<int|string>>|null$countryCallingCodeToRegionCodeMap
Return values
PhoneNumberUtilinstance

◆ getInvalidExampleNumber()

libphonenumber\PhoneNumberUtil::getInvalidExampleNumber ( string $regionCode)

Gets an invalid number for the specified region.

This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid short number/code for this region. Validity checking such numbers is handled with ShortNumberInfo.

Parameters
string$regionCodeThe region for which an example number is needed
Return values
PhoneNumber|nullAn invalid number for the specified region. Returns null when an unsupported region or the region 001 (Earth) is passed in.

◆ getLengthOfGeographicalAreaCode()

libphonenumber\PhoneNumberUtil::getLengthOfGeographicalAreaCode ( PhoneNumber $number)

Gets the length of the geographical area code from the nationalNumber field of the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number.

It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used:

$phoneUtil = PhoneNumberUtil::getInstance(); $number = $phoneUtil->parse("16502530000", "US"); $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);

$areaCodeLength = $phoneUtil->getLengthOfGeographicalAreaCode($number); if ($areaCodeLength > 0) { $areaCode = substr($nationalSignificantNumber, 0,$areaCodeLength); $subscriberNumber = substr($nationalSignificantNumber, $areaCodeLength); } else { $areaCode = ""; $subscriberNumber = $nationalSignificantNumber; }

N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general nationalNumber instead. Read the following carefully before deciding to use this method:

  • geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces.
  • subscriber numbers may not be diallable from all devices (notably mobile devices, which typically requires the full national_number to be dialled in most regions).
  • most non-geographical numbers have no area codes, including numbers from non-geographical entities
  • some geographical numbers have no area codes.
Parameters
PhoneNumber$numberPhoneNumber object for which clients want to know the length of the area code.
Return values
intthe length of area code of the PhoneNumber object passed in.

◆ getLengthOfNationalDestinationCode()

libphonenumber\PhoneNumberUtil::getLengthOfNationalDestinationCode ( PhoneNumber $number)

Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number.

The NDC of a phone number is normally the first group of digit(s) right after the country calling code when the number is formatted in the international format, if there is a subscriber number part that follows.

follows.

N.B.: similar to an area code, not all numbers have an NDC!

An example of how this could be used:

$phoneUtil = PhoneNumberUtil::getInstance(); $number = $phoneUtil->parse("18002530000", "US"); $nationalSignificantNumber = $phoneUtil->getNationalSignificantNumber($number);

$nationalDestinationCodeLength = $phoneUtil->getLengthOfNationalDestinationCode($number); if ($nationalDestinationCodeLength > 0) { $nationalDestinationCode = substr($nationalSignificantNumber, 0, $nationalDestinationCodeLength); $subscriberNumber = substr($nationalSignificantNumber, $nationalDestinationCodeLength); } else { $nationalDestinationCode = ""; $subscriberNumber = $nationalSignificantNumber; }

Refer to the unit tests to see the difference between this function and getLengthOfGeographicalAreaCode.

Parameters
PhoneNumber$numberthe PhoneNumber object for which clients want to know the length of the NDC.
Return values
intthe length of NDC of the PhoneNumber object passed in, which could be zero

◆ getNationalSignificantNumber()

libphonenumber\PhoneNumberUtil::getNationalSignificantNumber ( PhoneNumber $number)

Gets the national significant number of the phone number.

Note a national significant number doesn't contain a national prefix or any formatting.

Parameters
PhoneNumber$numberthe phone number for which the national significant number is needed
Return values
stringthe national significant number of the PhoneNumber object passed in

◆ getNddPrefixForRegion()

libphonenumber\PhoneNumberUtil::getNddPrefixForRegion ( string $regionCode,
bool $stripNonDigits )

Returns the national dialling prefix for a specific region.

For example, this would be 1 for the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return null.

Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required.

Parameters
string$regionCodethe region that we want to get the dialling prefix for
boolean$stripNonDigitstrue to strip non-digits from the national dialling prefix
Return values
string|nullthe dialling prefix for the region denoted by regionCode

◆ getNumberDescByType()

libphonenumber\PhoneNumberUtil::getNumberDescByType ( PhoneMetadata $metadata,
int $type )
protected
Parameters
int$typePhoneNumberType

◆ getNumberType()

libphonenumber\PhoneNumberUtil::getNumberType ( PhoneNumber $number)

Gets the type of a valid phone number.

Parameters
PhoneNumber$numberthe number the phone number that we want to know the type
Return values
intPhoneNumberType the type of the phone number, or UNKNOWN if it is invalid

◆ getNumberTypeHelper()

libphonenumber\PhoneNumberUtil::getNumberTypeHelper ( string $nationalNumber,
PhoneMetadata $metadata )
protected

Returns the type of number passed in i.e Toll free, premium.

Return values
intPhoneNumberType constant

◆ getRegionCodeForCountryCode()

libphonenumber\PhoneNumberUtil::getRegionCodeForCountryCode ( int $countryCallingCode)

Returns the region code that matches the specific country calling code.

In the case of no region code being found, ZZ will be returned. In the case of multiple regions, the one designated in the metadata as the "main" region for this calling code will be returned. If the countryCallingCode entered is valid but doesn't match a specific region (such as in the case of non-geographical calling codes like 800) the value "001" will be returned (corresponding to the value for World in the UN M.49 schema).

◆ getRegionCodeForNumber()

libphonenumber\PhoneNumberUtil::getRegionCodeForNumber ( PhoneNumber $number)

Returns the region where a phone number is from.

This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers).

Parameters
PhoneNumber$numberthe phone number whose origin we want to know
Return values
null|stringthe region where the phone number is from, or null if no region matches this calling code

◆ getRegionCodeForNumberFromRegionList()

libphonenumber\PhoneNumberUtil::getRegionCodeForNumberFromRegionList ( PhoneNumber $number,
array $regionCodes )
protected

Returns the region code for a number from the list of region codes passing in.

Parameters
string[]$regionCodes

◆ getRegionCodesForCountryCode()

libphonenumber\PhoneNumberUtil::getRegionCodesForCountryCode ( int $countryCallingCode)

Returns a list with the region codes that match the specific country calling code.

For non-geographical country calling codes, the region code 001 is returned. Also, in the case of no region code being found, an empty list is returned.

Return values
string[]

◆ getSupportedCallingCodes()

libphonenumber\PhoneNumberUtil::getSupportedCallingCodes ( )

Returns all country calling codes the library has metadata for, covering both non-geographical entities (global network calling codes) and those used for geographical entities.

This could be used to populate a drop-down box of country calling codes for a phone-number widget, for instance.

Return values
int[]An unordered array of the country calling codes for every geographical and non-geographical entity the library supports

◆ getSupportedGlobalNetworkCallingCodes()

libphonenumber\PhoneNumberUtil::getSupportedGlobalNetworkCallingCodes ( )

Returns all global network calling codes the library has metadata for.

Return values
int[]An unordered array of the country calling codes for every non-geographical entity the library supports

◆ getSupportedRegions()

libphonenumber\PhoneNumberUtil::getSupportedRegions ( )

Returns all regions the library has metadata for.

Return values
string[]An unordered array of the two-letter region codes for every geographical region the library supports

◆ getSupportedTypesForNonGeoEntity()

libphonenumber\PhoneNumberUtil::getSupportedTypesForNonGeoEntity ( int $countryCallingCode)

Returns the types for a country-code belonging to a non-geographical entity which the library has metadata for.

Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographical entity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN.

Return values
array<int>Array of PhoneNumberType's

◆ getSupportedTypesForRegion()

libphonenumber\PhoneNumberUtil::getSupportedTypesForRegion ( string $regionCode)

Returns the types for a given region which the library has metadata for.

Will not include FIXED_LINE_OR_MOBILE (if the numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN.

No types will be returned for invalid or unknown region codes.

Return values
array<int>Array of PhoneNumberType's

◆ isAlphaNumber()

libphonenumber\PhoneNumberUtil::isAlphaNumber ( string $number)

Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT.

A valid vanity number will start with at least 3 digits and will have three or more alpha characters. This does not do region-specific checks - to work out if this number is actually valid for a region, it should be parsed and methods such as isPossibleNumberWithReason and isValidNumber should be used.

Parameters
string$numberthe number that needs to be checked
Return values
booltrue if the number is a valid vanity number

◆ isMobileNumberPortableRegion()

libphonenumber\PhoneNumberUtil::isMobileNumberPortableRegion ( string $regionCode)

Returns true if the supplied region supports mobile number portability.

Returns false for invalid, unknown or regions that don't support mobile number portability.

Parameters
string$regionCodethe region for which we want to know whether it supports mobile number portability or not.

◆ isNANPACountry()

libphonenumber\PhoneNumberUtil::isNANPACountry ( string $regionCode)

Checks if this is a region under the North American Numbering Plan Administration (NANPA).

Return values
booleantrue if regionCode is one of the regions under NANPA

◆ isNumberGeographical()

libphonenumber\PhoneNumberUtil::isNumberGeographical ( PhoneNumber|int $phoneNumberObjOrType,
?int $countryCallingCode = null )

isNumberGeographical(PhoneNumber)

Tests whether a phone number has a geographical association. It checks if the number is associated with a certain region in the country to which it belongs. Note that this doesn't verify if the number is actually in use.

isNumberGeographical(PhoneNumberType, $countryCallingCode)

Tests whether a phone number has a geographical association, as represented by its type and the country it belongs to.

This version exists since calculating the phone number type is expensive; if we have already done this, we don't want to do it again.

Parameters
PhoneNumber | int$phoneNumberObjOrTypeA PhoneNumber object, or a PhoneNumberType integer
int | null$countryCallingCodeUsed when passing a PhoneNumberType

◆ isNumberMatch()

libphonenumber\PhoneNumberUtil::isNumberMatch ( PhoneNumber|string $firstNumberIn,
PhoneNumber|string $secondNumberIn )

Takes two phone numbers and compares them for equality.

Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. Returns NO_MATCH otherwise. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.

Parameters
$firstNumberInPhoneNumber|string First number to compare. If it is a string it can contain formatting, and can have country calling code specified with + at the start.
$secondNumberInPhoneNumber|string Second number to compare. If it is a string it can contain formatting, and can have country calling code specified with + at the start.
Exceptions
InvalidArgumentException
Return values
int{MatchType} NOT_A_NUMBER, NO_MATCH,

◆ isPossibleNumber()

libphonenumber\PhoneNumberUtil::isPossibleNumber ( PhoneNumber|string $number,
?string $regionDialingFrom = null )

Check whether a phone number is a possible number given a number in the form of a string, and the region where the number could be dialed from.

It provides a more lenient check than isValidNumber. See isPossibleNumber(PhoneNumber) for details.

Convenience wrapper around isPossibleNumberWithReason. Instead of returning the reason for failure, this method returns a boolean value. For failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.

Note: There are two ways to call this method.

isPossibleNumber(PhoneNumber $numberObject) isPossibleNumber(string '+441174960126', string 'GB')

Parameters
PhoneNumber | string$numberthe number that needs to be checked, in the form of a string
string | null$regionDialingFromthe region that we are expecting the number to be dialed from. Note this is different from the region where the number belongs. For example, the number +1 650 253 0000 is a number that belongs to US. When written in this form, it can be dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any region which uses an international dialling prefix of 00. When it is written as 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it can only be dialed from within a smaller area in the US (Mountain View, CA, to be more specific).
Return values
booleantrue if the number is possible

◆ isPossibleNumberForType()

libphonenumber\PhoneNumberUtil::isPossibleNumberForType ( PhoneNumber $number,
int $type )

Convenience wrapper around isPossibleNumberForTypeWithReason.

Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it.

Parameters
PhoneNumber$numberThe number that needs to be checked
int$typePhoneNumberType The type we are interested in
Return values
booltrue if the number is possible for this particular type

◆ isPossibleNumberForTypeWithReason()

libphonenumber\PhoneNumberUtil::isPossibleNumberForTypeWithReason ( PhoneNumber $number,
int $type )

Check whether a phone number is a possible number of a particular type.

For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use getSupportedTypesForRegion or getSupportedTypesForNonGeoEntity respectively before calling this method to determine whether you should call it for this number at all.

This provides a more lenient check than isValidNumber in the following sense:

  1. It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
  2. For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because isValidNumber validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version.

There is a known issue with this method: if a number is possible only in a certain region among several regions that share the same country calling code, this method will consider only the "main" region. For example, +1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result, this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.

Parameters
PhoneNumber$numberthe number that needs to be checked
int$typethe PhoneNumberType we are interested in
Return values
inta ValidationResult object which indicates whether the number is possible

◆ isPossibleNumberWithReason()

libphonenumber\PhoneNumberUtil::isPossibleNumberWithReason ( PhoneNumber $number)

Check whether a phone number is a possible number.

It provides a more lenient check than isValidNumber in the following sense:

  1. It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number.
  2. It doesn't attempt to figure out the type of the number, but uses general rules which applies to all types of phone numbers in a region. Therefore, it is much faster than isValidNumber.
  3. For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because isValidNumber validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version.

There is a known issue with this method: if a number is possible only in a certain region among several regions that share the same country calling code, this method will consider only the "main" region. For example, +1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result, this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.

Parameters
PhoneNumber$numberthe number that needs to be checked
Return values
inta ValidationResult object which indicates whether the number is possible

◆ isValidNumber()

libphonenumber\PhoneNumberUtil::isValidNumber ( PhoneNumber $number)

Tests whether a phone number matches a valid pattern.

Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. It only verifies whether the parsed, canonicalised number is valid: not whether a particular series of digits entered by the user is diallable from the region provided when parsing. For example, the number +41 (0) 78 927 2696 can be parsed into a number with country code "41" and national significant number "789272696". This is valid, while the original string is not diallable.

Parameters
PhoneNumber$numberthe phone number that we want to validate
Return values
booleanthat indicates whether the number is of a valid pattern

◆ isValidNumberForRegion()

libphonenumber\PhoneNumberUtil::isValidNumberForRegion ( PhoneNumber $number,
string $regionCode )

Tests whether a phone number is valid for a certain region.

Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use isValidNumber instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable.

Parameters
PhoneNumber$numberthe phone number that we want to validate
string$regionCodethe region that we want to validate the phone number for
Return values
booleanthat indicates whether the number is of a valid pattern

◆ isViablePhoneNumber()

static libphonenumber\PhoneNumberUtil::isViablePhoneNumber ( string $number)
static

Checks to see if the string of characters could possibly be a phone number at all.

At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method extractPossibleNumber.

Parameters
string$numberto be checked for viability as a phone number
Return values
booleantrue if the number could be a phone number of some sort, otherwise false

◆ maybeAppendFormattedExtension()

libphonenumber\PhoneNumberUtil::maybeAppendFormattedExtension ( PhoneNumber $number,
?PhoneMetadata $metadata,
int $numberFormat,
string & $formattedNumber )
protected

Appends the formatted extension of a phone number to formattedNumber, if the phone number had an extension specified.

Parameters
int$numberFormatPhoneNumberFormat

◆ maybeExtractCountryCode()

libphonenumber\PhoneNumberUtil::maybeExtractCountryCode ( string $number,
?PhoneMetadata $defaultRegionMetadata,
string & $nationalNumber,
bool $keepRawInput,
PhoneNumber $phoneNumber )

Tries to extract a country calling code from a number.

This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways:

  • by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits
  • by stripping the '+' sign if present and then looking at the next digits
  • by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such.

It will throw a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region.

Parameters
string$numbernon-normalized telephone number that we wish to extract a country calling code from - may begin with '+'
PhoneMetadata | null$defaultRegionMetadatametadata about the region this number may be from
string$nationalNumbera string buffer to store the national significant number in, in the case that a country calling code was extracted. The number is appended to any existing contents. If no country calling code was extracted, this will be left unchanged.
bool$keepRawInputtrue if the country_code_source and preferred_carrier_code fields of phoneNumber should be populated.
PhoneNumber$phoneNumberthe PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keepCountryCodeSource is true.
Return values
intthe country calling code extracted or 0 if none could be extracted
Exceptions
NumberParseException

◆ maybeStripExtension()

libphonenumber\PhoneNumberUtil::maybeStripExtension ( string & $number)
protected

Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it.

Parameters
string$numberthe non-normalized telephone number that we wish to strip the extension from
Return values
stringthe phone extension

◆ maybeStripInternationalPrefixAndNormalize()

libphonenumber\PhoneNumberUtil::maybeStripInternationalPrefixAndNormalize ( string & $number,
string $possibleIddPrefix )

Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes the resulting number, and indicates if an international prefix was present.

Parameters
string$numberthe non-normalized telephone number that we wish to strip any international dialing prefix from.
string$possibleIddPrefixstring the international direct dialing prefix from the region we think this number may be dialed in
Return values
intthe corresponding CountryCodeSource if an international dialing prefix could be removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did not seem to be in international format.

◆ maybeStripNationalPrefixAndCarrierCode()

libphonenumber\PhoneNumberUtil::maybeStripNationalPrefixAndCarrierCode ( string & $number,
PhoneMetadata $metadata,
?string & $carrierCode )

Strips any national prefix (such as 0, 1) present in the number provided.

Parameters
string$numberthe normalized telephone number that we wish to strip any national dialing prefix from
PhoneMetadata$metadatathe metadata for the region that we think this number is from
string | null$carrierCodea place to insert the carrier code if one is extracted
Return values
booltrue if a national prefix or carrier code (or both) could be extracted.

◆ normalize()

static libphonenumber\PhoneNumberUtil::normalize ( string $number)
static

Normalizes a string of characters representing a phone number.

This performs the following conversions: Punctuation is stripped. For ALPHA/VANITY numbers: Letters are converted to their numeric representation on a telephone keypad. The keypad used here is the one defined in ITU Recommendation E.161. This is only done if there are 3 or more letters in the number, to lessen the risk that such letters are typos. For other numbers:

  • Wide-ascii digits are converted to normal ASCII (European) digits.
  • Arabic-Indic numerals are converted to European numerals.
  • Spurious alpha characters are stripped.
Parameters
string$numbera string of characters representing a phone number.
Return values
stringthe normalized string version of the phone number.

◆ normalizeDiallableCharsOnly()

static libphonenumber\PhoneNumberUtil::normalizeDiallableCharsOnly ( string $number)
static

Normalizes a string of characters representing a phone number.

This strips all characters which are not diallable on a mobile phone keypad (including all non-ASCII digits).

Parameters
string$numbera string of characters representing a phone number
Return values
stringthe normalized string version of the phone number

◆ normalizeDigitsOnly()

static libphonenumber\PhoneNumberUtil::normalizeDigitsOnly ( string $number)
static

Normalizes a string of characters representing a phone number.

This converts wide-ascii and arabic-indic numerals to European numerals, and strips punctuation and alpha characters.

Parameters
string$numbera string of characters representing a phone number
Return values
stringthe normalized string version of the phone number

◆ normalizeHelper()

static libphonenumber\PhoneNumberUtil::normalizeHelper ( string $number,
array $normalizationReplacements,
bool $removeNonMatches )
staticprotected

Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein, and stripping all other characters if removeNonMatches is true.

Parameters
string$numbera string of characters representing a phone number
array<string,string>$normalizationReplacements a mapping of characters to what they should be replaced by in the normalized version of the phone number.
bool$removeNonMatchesindicates whether characters that are not able to be replaced. should be stripped from the number. If this is false, they will be left unchanged in the number.
Return values
stringthe normalized string version of the phone number.

◆ parse()

libphonenumber\PhoneNumberUtil::parse ( string $numberToParse,
?string $defaultRegion = null,
?PhoneNumber $phoneNumber = null,
bool $keepRawInput = false )

Parses a string and returns it as a phone number in proto buffer format.

The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading “Tel: ”) and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT".

This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with isValidNumber.

Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then call *#parseAndKeepRawInput instead.

Parameters
string$numberToParsenumber that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension.
string | null$defaultRegionregion that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.
Return values
PhoneNumbera phone number proto buffer filled with the parsed number
Exceptions
NumberParseExceptionif the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +)

◆ parseAndKeepRawInput()

libphonenumber\PhoneNumberUtil::parseAndKeepRawInput ( string $numberToParse,
?string $defaultRegion,
?PhoneNumber $phoneNumber = null )

Parses a string and returns it in proto buffer format.

This method differs from parse in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.

Parameters
string$numberToParsenumber that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format.
string | null$defaultRegionregion that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country calling code for the number in this case would be stored as that of the default region supplied.
Return values
PhoneNumbera phone number proto buffer filled with the parsed number

◆ parseHelper()

libphonenumber\PhoneNumberUtil::parseHelper ( string $numberToParse,
?string $defaultRegion,
bool $keepRawInput,
bool $checkRegion,
PhoneNumber $phoneNumber )
protected

Parses a string and fills up the phoneNumber.

This method is the same as the public parse() method, with the exception that it allows the default region to be null, for use by isNumberMatch(). checkRegion should be set to false if it is permitted for the default region to be null or unknown ("ZZ").

Exceptions
NumberParseException

◆ parsePrefixAsIdd()

libphonenumber\PhoneNumberUtil::parsePrefixAsIdd ( string $iddPattern,
string & $number )
protected

Strips the IDD from the start of the number if present.

Helper function used by maybeStripInternationalPrefixAndNormalize.

◆ prefixNumberWithCountryCallingCode()

libphonenumber\PhoneNumberUtil::prefixNumberWithCountryCallingCode ( int $countryCallingCode,
int $numberFormat,
string & $formattedNumber )
protected

A helper function that is used by format and formatByPattern.

Parameters
int$numberFormatPhoneNumberFormat

◆ rawInputContainsNationalPrefix()

libphonenumber\PhoneNumberUtil::rawInputContainsNationalPrefix ( string $rawInput,
string $nationalPrefix,
string $regionCode )
protected

Check if rawInput, which is assumed to be in the national format, has a national prefix.

The national prefix is assumed to be in digits-only form.

◆ testNumberLength()

libphonenumber\PhoneNumberUtil::testNumberLength ( string $number,
PhoneMetadata $metadata,
int $type = PhoneNumberType::UNKNOWN )
protected

Helper method to check a number against possible lengths for this number type, and determine whether it matches, or is too short or too long.

Parameters
int$typePhoneNumberType
Return values
intValidationResult

◆ truncateTooLongNumber()

libphonenumber\PhoneNumberUtil::truncateTooLongNumber ( PhoneNumber $number)

Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version.

If no valid number could be extracted, the PhoneNumber object passed in will not be modified.

Parameters
PhoneNumber$numbera PhoneNumber object which contains a number that is too long to be valid.
Return values
booleantrue if a valid phone number can be successfully extracted.

Member Data Documentation

◆ $ALL_PLUS_NUMBER_GROUPING_SYMBOLS

array<string,string> array libphonenumber\PhoneNumberUtil::$ALL_PLUS_NUMBER_GROUPING_SYMBOLS
staticprotected

Separate map of all symbols that we wish to retain when formatting alpha numbers.

This includes digits, ASCII letters and number grouping symbols such as "-" and " ".

◆ $countryCallingCodeToRegionCodeMap

array<int,string[]> array libphonenumber\PhoneNumberUtil::$countryCallingCodeToRegionCodeMap = []
protected

A mapping from a country calling code to the region codes which denote the region represented by that country calling code.

In the case of multiple regions sharing a calling code, such as the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be first.

◆ $EXTN_PATTERNS_FOR_PARSING

string libphonenumber\PhoneNumberUtil::$EXTN_PATTERNS_FOR_PARSING
staticprotected

Regexp of all possible ways to write extensions, for use when parsing.

This will be run as a case-insensitive regexp match. Wide character versions are also provided after each ASCII version.

◆ $VALID_PHONE_NUMBER

string libphonenumber\PhoneNumberUtil::$VALID_PHONE_NUMBER
staticprotected

Regular expression of viable phone numbers.

This is location independent. Checks we have at least three leading digits, and only valid punctuation, alpha characters and digits in the phone number. Does not include extension data. The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at the start. Corresponds to the following: [digits]{minLengthNsn}| plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*

The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered as "15" etc, but only if there is no punctuation in them. The second expression restricts the number of digits to three or more, but then allows them to be in international form, and to have alpha-characters and punctuation.

Note VALID_PUNCTUATION starts with a -, so must be the first in the range.

◆ ALPHA_MAPPINGS

const libphonenumber\PhoneNumberUtil::ALPHA_MAPPINGS
protected
Initial value:
= [
'A' => '2',
'B' => '2',
'C' => '2',
'D' => '3',
'E' => '3',
'F' => '3',
'G' => '4',
'H' => '4',
'I' => '4',
'J' => '5',
'K' => '5',
'L' => '5',
'M' => '6',
'N' => '6',
'O' => '6',
'P' => '7',
'Q' => '7',
'R' => '7',
'S' => '7',
'T' => '8',
'U' => '8',
'V' => '8',
'W' => '9',
'X' => '9',
'Y' => '9',
'Z' => '9',
]

Only upper-case variants of alpha characters are stored.

◆ ASCII_DIGIT_MAPPINGS

const libphonenumber\PhoneNumberUtil::ASCII_DIGIT_MAPPINGS
protected
Initial value:
= [
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
]

Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and ALL_PLUS_NUMBER_GROUPING_SYMBOLS.

◆ COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES

const libphonenumber\PhoneNumberUtil::COUNTRIES_WITHOUT_NATIONAL_PREFIX_WITH_AREA_CODES
protected
Initial value:
= [
52,
]

Set of country codes that doesn't have national prefix, but it has area codes.

◆ DIALLABLE_CHAR_MAPPINGS

const libphonenumber\PhoneNumberUtil::DIALLABLE_CHAR_MAPPINGS
protected
Initial value:
= self::ASCII_DIGIT_MAPPINGS
+ [self::PLUS_SIGN => self::PLUS_SIGN]
+ ['*' => '*', '#' => '#']

◆ GEO_MOBILE_COUNTRIES

const libphonenumber\PhoneNumberUtil::GEO_MOBILE_COUNTRIES
protected
Initial value:
= [
52,
54,
55,
62,
] + self::GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES

Set of country calling codes that have geographically assigned mobile numbers.

This may not be complete; we add calling codes case by case, as we find geographical mobile numbers or hear from user reports. Note that countries like the US, where we can't distinguish between fixed-line or mobile numbers, are not listed here, since we consider FIXED_LINE_OR_MOBILE to be a possibly geographically-related type anyway (like FIXED_LINE).

◆ GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES

const libphonenumber\PhoneNumberUtil::GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES
protected
Initial value:
= [
86,
]

Set of country codes that have geographically assigned mobile numbers (see GEO_MOBILE_COUNTRIES below) which are not based on area codes.

For example, in China mobile numbers start with a carrier indicator, and beyond that are geographically assigned: this carrier indicator is not considered to be an area code.

◆ MOBILE_TOKEN_MAPPINGS

const libphonenumber\PhoneNumberUtil::MOBILE_TOKEN_MAPPINGS
protected
Initial value:
= [
'54' => '9',
]

Map of country calling codes that use a mobile token before the area code.

One example of when this is relevant is when determining the length of the national destination code, which should be the length of the area code plus the length of the mobile token.


The documentation for this class was generated from the following file: