PHP Class libphonenumber\PhoneNumberUtil

If you use this library, and want to be notified about important changes, please sign up to our mailing list. NOTE: A lot of methods in this class require Region Code strings. These must be provided using ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes can be found here: http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm

Author: Shaopeng Jia
Author: Lara Rennie
Datei anzeigen Open project: giggsey/libphonenumber-for-php Class Usage Examples

Public Properties

Property Type Description
$PLUS_CHARS_PATTERN

Protected Properties

Property Type Description
$ALL_PLUS_NUMBER_GROUPING_SYMBOLS array 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 " ".
$ALPHA_MAPPINGS array Only upper-case variants of alpha characters are stored.
$ALPHA_PHONE_MAPPINGS array For performance reasons, amalgamate both into one map.
$CAPTURING_DIGIT_PATTERN
$CAPTURING_EXTN_DIGITS
$DIALLABLE_CHAR_MAPPINGS
$EXTN_PATTERN
$EXTN_PATTERNS_FOR_PARSING String 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.
$GEO_MOBILE_COUNTRIES array 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 array 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.
$MIN_LENGTH_PHONE_NUMBER_PATTERN
$MOBILE_TOKEN_MAPPINGS array 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.
$SECOND_NUMBER_START_PATTERN
$SEPARATOR_PATTERN
$UNWANTED_END_CHAR_PATTERN
$VALID_PHONE_NUMBER string 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.
$VALID_PHONE_NUMBER_PATTERN
$VALID_START_CHAR_PATTERN
$asciiDigitMappings array Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
$countryCallingCodeToRegionCodeMap array 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.
$countryCodesForNonGeographicalRegion array The set of county calling codes that map to the non-geo entity region ("001").
$instance PhoneNumberUtil
$metadataSource libphonenumber\MetadataSourceInterface
$nanpaRegions array The set of regions that share country calling code 1.
$numericCharacters
$supportedRegions array The set of regions the library supports.

Public Methods

Method Description
canBeInternationallyDialled ( PhoneNumber $number ) : boolean 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.
chooseFormattingPatternForNumber ( array $availableFormats, string $nationalNumber ) : NumberFormat | null
convertAlphaCharactersInNumber ( string $number ) : string Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.
extractPossibleNumber ( integer $number ) : string 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.
format ( PhoneNumber $number, integer $numberFormat ) : string 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.
formatByPattern ( PhoneNumber $number, integer $numberFormat, array $userDefinedFormats ) : String 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.
formatInOriginalFormat ( PhoneNumber $number, string $regionCallingFrom ) : string Formats a phone number using the original phone number format that the number is parsed from.
formatNationalNumberWithCarrierCode ( PhoneNumber $number, string $carrierCode ) : string Formats a phone number in national format for dialing using the carrier as specified in the {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If {@code carrierCode} contains an empty string, returns the number in national format without any carrier code.
formatNationalNumberWithPreferredCarrierCode ( PhoneNumber $number, string $fallbackCarrierCode ) : string 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 {@code fallbackCarrierCode} passed in instead. If there is no {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty string, return the number in national format without any carrier code.
formatNumberForMobileDialing ( PhoneNumber $number, string $regionCallingFrom, boolean $withFormatting ) : string 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.
formatOutOfCountryCallingNumber ( PhoneNumber $number, string $regionCallingFrom ) : string 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.
formatOutOfCountryKeepingAlphaChars ( PhoneNumber $number, String $regionCallingFrom ) : String Formats a phone number for out-of-country dialing purposes.
formattingRuleHasFirstGroupOnly ( string $nationalPrefixFormattingRule ) : boolean Helper function to check if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix.
getCountryCodeForRegion ( string $regionCode ) : integer 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.
getCountryMobileToken ( integer $countryCallingCode ) : string 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.
getExampleNumber ( $regionCode ) : PhoneNumber Gets a valid number for the specified region.
getExampleNumberForNonGeoEntity ( integer $countryCallingCode ) : PhoneNumber Gets a valid number for the specified country calling code for a non-geographical entity.
getExampleNumberForType ( string | integer $regionCodeOrType, integer $type = null ) : PhoneNumber Gets a valid number for the specified region and number type.
getInstance ( string $baseFileLocation = self::META_DATA_FILE_PREFIX, array $countryCallingCodeToRegionCodeMap = null, libphonenumber\MetadataLoaderInterface $metadataLoader = null, libphonenumber\MetadataSourceInterface $metadataSource = null ) : PhoneNumberUtil Gets a {@link 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.
getInvalidExampleNumber ( string $regionCode ) : PhoneNumber | null 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 {@link ShortNumberInfo}.
getLengthOfGeographicalAreaCode ( PhoneNumber $number ) : integer Gets the length of the geographical area code from the {@code 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:
getLengthOfNationalDestinationCode ( PhoneNumber $number ) : integer 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. An example of how this could be used:
getMetadataForNonGeographicalRegion ( integer $countryCallingCode ) : PhoneMetadata
getMetadataForRegion ( string $regionCode ) : PhoneMetadata Returns the metadata for the given region code or {@code null} if the region code is invalid or unknown.
getNationalSignificantNumber ( PhoneNumber $number ) : string Gets the national significant number of the a phone number. Note a national significant number doesn't contain a national prefix or any formatting.
getNddPrefixForRegion ( string $regionCode, boolean $stripNonDigits ) : string 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.
getNumberType ( PhoneNumber $number ) : integer Gets the type of a phone number.
getRegionCodeForCountryCode ( integer $countryCallingCode ) : string 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 ( PhoneNumber $number ) : null | string Returns the region where a phone number is from. This could be used for geocoding at the region level.
getRegionCodesForCountryCode ( integer $countryCallingCode ) : array 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.
getSupportedGlobalNetworkCallingCodes ( ) : array Convenience method to get a list of what global network calling codes the library has metadata for.
getSupportedRegions ( ) : array Convenience method to get a list of what regions the library has metadata for.
isAlphaNumber ( string $number ) : boolean 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 {@link #isPossibleNumberWithReason} and {@link #isValidNumber} should be used.
isLeadingZeroPossible ( integer $countryCallingCode ) : boolean Checks whether the country calling code is from a region whose national significant number could contain a leading zero. An example of such a region is Italy. Returns false if no metadata for the country is found.
isMobileNumberPortableRegion ( string $regionCode ) : boolean Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability.
isNANPACountry ( string $regionCode ) : boolean Checks if this is a region under the North American Numbering Plan Administration (NANPA).
isNumberGeographical ( PhoneNumber | integer $phoneNumberObjOrType, integer | null $countryCallingCode = null ) : boolean isNumberGeographical(PhoneNumber)
isNumberMatch ( $firstNumberIn, $secondNumberIn ) : integer Takes two phone numbers and compares them for equality.
isNumberMatchingDesc ( string $nationalNumber, PhoneNumberDesc $numberDesc ) : boolean
isPossibleNumber ( PhoneNumber | string $number, string $regionDialingFrom = null ) : boolean 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 {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
isPossibleNumberWithReason ( PhoneNumber $number ) : integer Check whether a phone number is a possible number. It provides a more lenient check than {@link #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.
isValidNumber ( PhoneNumber $number ) : boolean 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.
isValidNumberForRegion ( PhoneNumber $number, string $regionCode ) : boolean 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.
isViablePhoneNumber ( string $number ) : boolean 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.
maybeExtractCountryCode ( string $number, PhoneMetadata $defaultRegionMetadata = null, string &$nationalNumber, boolean $keepRawInput, PhoneNumber $phoneNumber ) : integer 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.
maybeStripInternationalPrefixAndNormalize ( string &$number, string $possibleIddPrefix ) : integer 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 ) : boolean Strips any national prefix (such as 0, 1) present in the number provided.
normalize ( string &$number ) : string Normalizes a string of characters representing a phone number. This performs the following conversions: Punctuation is stripped.
normalizeDiallableCharsOnly ( string $number ) : string 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).
normalizeDigits ( string $number, boolean $keepNonDigits ) : string
normalizeDigitsOnly ( $number ) : string 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.
parse ( string $numberToParse, string $defaultRegion, PhoneNumber $phoneNumber = null, boolean $keepRawInput = false ) : PhoneNumber 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.
parseAndKeepRawInput ( string $numberToParse, string $defaultRegion, PhoneNumber $phoneNumber = null ) : PhoneNumber Parses a string and returns it in proto buffer format. This method differs from {@link #parse} in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.
resetInstance ( ) Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
setItalianLeadingZerosForPhoneNumber ( string $nationalNumber, PhoneNumber $phoneNumber ) A helper function to set the values related to leading zeros in a PhoneNumber.
truncateTooLongNumber ( PhoneNumber $number ) : boolean 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.

Protected Methods

Method Description
__construct ( libphonenumber\MetadataSourceInterface $metadataSource, $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 ) : boolean 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.
createExtnPattern ( string $singleExtnSymbols ) : string Helper initialiser method to create the regular-expression pattern to match extensions, allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
extractCountryCode ( string &$fullNumber, string &$nationalNumber ) : integer Extracts country calling code from fullNumber, returns it and places the remaining number in nationalNumber.
formatNsn ( string $number, PhoneMetadata $metadata, integer $numberFormat, null | string $carrierCode = null ) : string 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.
formatNsnUsingPattern ( string $nationalNumber, NumberFormat $formattingPattern, integer $numberFormat, null | string $carrierCode = null ) : string Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.
getCountryCodeForValidRegion ( string $regionCode ) : integer 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.
getMetadataForRegionOrCallingCode ( integer $countryCallingCode, string $regionCode ) : PhoneMetadata
getNumberDescByType ( PhoneMetadata $metadata, integer $type ) : PhoneNumberDesc
getNumberTypeHelper ( string $nationalNumber, PhoneMetadata $metadata ) : integer
getRegionCodeForNumberFromRegionList ( PhoneNumber $number, array $regionCodes ) : null | string
getValidPhoneNumberPattern ( ) : string 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.
hasFormattingPatternForNumber ( PhoneNumber $number ) : boolean
hasUnexpectedItalianLeadingZero ( PhoneNumber $number ) : boolean Returns true if a number is from a region whose national significant number couldn't contain a leading zero, but has the italian_leading_zero field set to true.
hasValidCountryCallingCode ( integer $countryCallingCode ) : boolean Helper function to check the country calling code is valid.
init ( )
initAlphaPhoneMappings ( )
initCapturingExtnDigits ( )
initDiallableCharMappings ( )
initExtnPattern ( )
initExtnPatterns ( )
initMobileTokenMappings ( )
initValidStartCharPattern ( )
isNationalNumberSuffixOfTheOther ( PhoneNumber $firstNumber, PhoneNumber $secondNumber ) : boolean Returns true when one national number is the suffix of the other or both are the same.
isValidRegionCode ( string $regionCode ) : boolean Helper function to check region code is not unknown or null.
maybeAppendFormattedExtension ( PhoneNumber $number, PhoneMetadata | null $metadata, integer $numberFormat, string &$formattedNumber ) Appends the formatted extension of a phone number to formattedNumber, if the phone number had an extension specified.
maybeStripExtension ( string &$number ) : string 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.
normalizeHelper ( string $number, array $normalizationReplacements, boolean $removeNonMatches ) : string 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.
parseHelper ( string $numberToParse, string $defaultRegion, boolean $keepRawInput, boolean $checkRegion, PhoneNumber $phoneNumber ) 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").
parsePrefixAsIdd ( string $iddPattern, string &$number ) : boolean Strips the IDD from the start of the number if present. Helper function used by maybeStripInternationalPrefixAndNormalize.
prefixNumberWithCountryCallingCode ( integer $countryCallingCode, integer $numberFormat, string &$formattedNumber ) A helper function that is used by format and formatByPattern.
rawInputContainsNationalPrefix ( string $rawInput, string $nationalPrefix, string $regionCode ) : boolean 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.
stringEndsWithString ( $hayStack, $needle )
testNumberLength ( string $number, PhoneNumberDesc $phoneNumberDesc ) : integer Helper method to check a number against possible lengths for this number, and determine whether it matches, or is too short or too long. Currently, if a number pattern suggests that numbers of length 7 and 10 are possible, and a number in between these possible lengths is entered, such as of length 8, this will return TOO_LONG.

Method Details

__construct() protected method

This class implements a singleton, so the only constructor is protected.
protected __construct ( libphonenumber\MetadataSourceInterface $metadataSource, $countryCallingCodeToRegionCodeMap )
$metadataSource libphonenumber\MetadataSourceInterface
$countryCallingCodeToRegionCodeMap

buildNationalNumberForParsing() protected method

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.
protected buildNationalNumberForParsing ( string $numberToParse, string &$nationalNumber )
$numberToParse string
$nationalNumber string

canBeInternationallyDialled() public method

TODO: Make this method public when we have enough metadata to make it worthwhile.
public canBeInternationallyDialled ( PhoneNumber $number ) : boolean
$number PhoneNumber the phone-number for which we want to know whether it is diallable from outside the region
return boolean

checkRegionForParsing() protected method

Returns false if it cannot use the region provided and the region cannot be inferred.
protected checkRegionForParsing ( string $numberToParse, string $defaultRegion ) : boolean
$numberToParse string
$defaultRegion string
return boolean

chooseFormattingPatternForNumber() public method

public chooseFormattingPatternForNumber ( array $availableFormats, string $nationalNumber ) : NumberFormat | null
$availableFormats array
$nationalNumber string
return NumberFormat | null

convertAlphaCharactersInNumber() public static method

Converts all alpha characters in a number to their respective digits on a keypad, but retains existing formatting.
public static convertAlphaCharactersInNumber ( string $number ) : string
$number string
return string

createExtnPattern() protected static method

Helper initialiser method to create the regular-expression pattern to match extensions, allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
protected static createExtnPattern ( string $singleExtnSymbols ) : string
$singleExtnSymbols string
return string

extractCountryCode() protected method

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.
protected extractCountryCode ( string &$fullNumber, string &$nationalNumber ) : integer
$fullNumber string
$nationalNumber string
return integer

extractPossibleNumber() public static method

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.
public static extractPossibleNumber ( integer $number ) : string
$number integer the string that might contain a phone number
return string the 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() public method

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.
public format ( PhoneNumber $number, integer $numberFormat ) : string
$number PhoneNumber the phone number to be formatted
$numberFormat integer the PhoneNumberFormat the phone number should be formatted into
return string the formatted phone number

formatByPattern() public method

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.
public formatByPattern ( PhoneNumber $number, integer $numberFormat, array $userDefinedFormats ) : String
$number PhoneNumber the phone number to be formatted
$numberFormat integer the format the phone number should be formatted into
$userDefinedFormats array formatting rules specified by clients
return String the formatted phone number

formatInOriginalFormat() public method

The original format is embedded in the country_code_source field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into the NATIONAL format by default. When the number contains a leading zero and this is unexpected for this country, or we don't have a formatting pattern for the number, the method returns the raw input when it is available. Note this method guarantees no digit will be inserted, removed or modified as a result of formatting.
public formatInOriginalFormat ( PhoneNumber $number, string $regionCallingFrom ) : string
$number PhoneNumber the phone number that needs to be formatted in its original number format
$regionCallingFrom string the region whose IDD needs to be prefixed if the original number has one
return string the formatted phone number in its original number format

formatNationalNumberWithCarrierCode() public method

Formats a phone number in national format for dialing using the carrier as specified in the {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If {@code carrierCode} contains an empty string, returns the number in national format without any carrier code.
public formatNationalNumberWithCarrierCode ( PhoneNumber $number, string $carrierCode ) : string
$number PhoneNumber the phone number to be formatted
$carrierCode string the carrier selection code to be used
return string the formatted phone number in national format for dialing using the carrier as specified in the {@code carrierCode}

formatNationalNumberWithPreferredCarrierCode() public method

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

public formatNationalNumberWithPreferredCarrierCode ( PhoneNumber $number, string $fallbackCarrierCode ) : string
$number PhoneNumber the phone number to be formatted
$fallbackCarrierCode string the carrier selection code to be used, if none is found in the phone number itself
return string the formatted phone number in national format for dialing using the number's {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if none is found

formatNsn() protected method

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.
protected formatNsn ( string $number, PhoneMetadata $metadata, integer $numberFormat, null | string $carrierCode = null ) : string
$number string
$metadata PhoneMetadata
$numberFormat integer PhoneNumberFormat
$carrierCode null | string
return string

formatNsnUsingPattern() protected method

Note that carrierCode is optional - if null or an empty string, no carrier code replacement will take place.
protected formatNsnUsingPattern ( string $nationalNumber, NumberFormat $formattingPattern, integer $numberFormat, null | string $carrierCode = null ) : string
$nationalNumber string
$formattingPattern NumberFormat
$numberFormat integer PhoneNumberFormat
$carrierCode null | string
return string

formatNumberForMobileDialing() public method

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.
public formatNumberForMobileDialing ( PhoneNumber $number, string $regionCallingFrom, boolean $withFormatting ) : string
$number PhoneNumber the phone number to be formatted
$regionCallingFrom string the region where the call is being placed
$withFormatting boolean whether the number should be returned with formatting symbols, such as spaces and dashes.
return string the formatted phone number

formatOutOfCountryCallingNumber() public method

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.

public formatOutOfCountryCallingNumber ( PhoneNumber $number, string $regionCallingFrom ) : string
$number PhoneNumber the phone number to be formatted
$regionCallingFrom string the region where the call is being placed
return string the formatted phone number

formatOutOfCountryKeepingAlphaChars() public method

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.
public formatOutOfCountryKeepingAlphaChars ( PhoneNumber $number, String $regionCallingFrom ) : String
$number PhoneNumber the phone number that needs to be formatted
$regionCallingFrom String the region where the call is being placed
return String the formatted phone number

formattingRuleHasFirstGroupOnly() public static method

Helper function to check if the national prefix formatting rule has the first group only, i.e., does not start with the national prefix.
public static formattingRuleHasFirstGroupOnly ( string $nationalPrefixFormattingRule ) : boolean
$nationalPrefixFormattingRule string
return boolean

getCountryCodeForRegion() public method

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.
public getCountryCodeForRegion ( string $regionCode ) : integer
$regionCode string the region that we want to get the country calling code for
return integer the country calling code for the region denoted by regionCode

getCountryCodeForValidRegion() protected method

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.
protected getCountryCodeForValidRegion ( string $regionCode ) : integer
$regionCode string the region that we want to get the country calling code for
return integer the country calling code for the region denoted by regionCode

getCountryMobileToken() public static method

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.
public static getCountryMobileToken ( integer $countryCallingCode ) : string
$countryCallingCode integer the country calling code for which we want the mobile token
return string the mobile token, as a string, for the given country calling code

getExampleNumber() public method

Gets a valid number for the specified region.
public getExampleNumber ( $regionCode ) : PhoneNumber
return PhoneNumber a 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 {@link #getExampleNumberForNonGeoEntity} instead.

getExampleNumberForNonGeoEntity() public method

Gets a valid number for the specified country calling code for a non-geographical entity.
public getExampleNumberForNonGeoEntity ( integer $countryCallingCode ) : PhoneNumber
$countryCallingCode integer the country calling code for a non-geographical entity
return PhoneNumber a 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() public method

Gets a valid number for the specified region and number type.
public getExampleNumberForType ( string | integer $regionCodeOrType, integer $type = null ) : PhoneNumber
$regionCodeOrType string | integer the region for which an example number is needed
$type integer the PhoneNumberType of number that is needed
return PhoneNumber a 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 {@link #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() public static method

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

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

getInvalidExampleNumber() public method

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 {@link ShortNumberInfo}.
public getInvalidExampleNumber ( string $regionCode ) : PhoneNumber | null
$regionCode string The region for which an example number is needed
return PhoneNumber | null An invalid number for the specified region. Returns null when an unsupported region or the region 001 (Earth) is passed in.

getLengthOfGeographicalAreaCode() public method

$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 {@code 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.
public getLengthOfGeographicalAreaCode ( PhoneNumber $number ) : integer
$number PhoneNumber PhoneNumber object for which clients want to know the length of the area code.
return integer the length of area code of the PhoneNumber object passed in.

getLengthOfNationalDestinationCode() public method

$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 {@link #getLengthOfGeographicalAreaCode}.
public getLengthOfNationalDestinationCode ( PhoneNumber $number ) : integer
$number PhoneNumber the PhoneNumber object for which clients want to know the length of the NDC.
return integer the length of NDC of the PhoneNumber object passed in.

getMetadataForNonGeographicalRegion() public method

public getMetadataForNonGeographicalRegion ( integer $countryCallingCode ) : PhoneMetadata
$countryCallingCode integer
return PhoneMetadata

getMetadataForRegion() public method

Returns the metadata for the given region code or {@code null} if the region code is invalid or unknown.
public getMetadataForRegion ( string $regionCode ) : PhoneMetadata
$regionCode string
return PhoneMetadata

getMetadataForRegionOrCallingCode() protected method

protected getMetadataForRegionOrCallingCode ( integer $countryCallingCode, string $regionCode ) : PhoneMetadata
$countryCallingCode integer
$regionCode string
return PhoneMetadata

getNationalSignificantNumber() public method

Gets the national significant number of the a phone number. Note a national significant number doesn't contain a national prefix or any formatting.
public getNationalSignificantNumber ( PhoneNumber $number ) : string
$number PhoneNumber the phone number for which the national significant number is needed
return string the national significant number of the PhoneNumber object passed in

getNddPrefixForRegion() public method

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.

public getNddPrefixForRegion ( string $regionCode, boolean $stripNonDigits ) : string
$regionCode string the region that we want to get the dialling prefix for
$stripNonDigits boolean true to strip non-digits from the national dialling prefix
return string the dialling prefix for the region denoted by regionCode

getNumberDescByType() protected method

protected getNumberDescByType ( PhoneMetadata $metadata, integer $type ) : PhoneNumberDesc
$metadata PhoneMetadata
$type integer PhoneNumberType
return PhoneNumberDesc

getNumberType() public method

Gets the type of a phone number.
public getNumberType ( PhoneNumber $number ) : integer
$number PhoneNumber the number the phone number that we want to know the type
return integer PhoneNumberType the type of the phone number

getNumberTypeHelper() protected method

protected getNumberTypeHelper ( string $nationalNumber, PhoneMetadata $metadata ) : integer
$nationalNumber string
$metadata PhoneMetadata
return integer PhoneNumberType constant

getRegionCodeForCountryCode() public method

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).
public getRegionCodeForCountryCode ( integer $countryCallingCode ) : string
$countryCallingCode integer
return string

getRegionCodeForNumber() public method

Returns the region where a phone number is from. This could be used for geocoding at the region level.
public getRegionCodeForNumber ( PhoneNumber $number ) : null | string
$number PhoneNumber the phone number whose origin we want to know
return null | string the region where the phone number is from, or null if no region matches this calling code

getRegionCodeForNumberFromRegionList() protected method

protected getRegionCodeForNumberFromRegionList ( PhoneNumber $number, array $regionCodes ) : null | string
$number PhoneNumber
$regionCodes array
return null | string

getRegionCodesForCountryCode() public method

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.
public getRegionCodesForCountryCode ( integer $countryCallingCode ) : array
$countryCallingCode integer
return array

getSupportedGlobalNetworkCallingCodes() public method

Convenience method to get a list of what global network calling codes the library has metadata for.

getSupportedRegions() public method

Convenience method to get a list of what regions the library has metadata for.
public getSupportedRegions ( ) : array
return array

getValidPhoneNumberPattern() protected static method

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.
protected static getValidPhoneNumberPattern ( ) : string
return string

hasFormattingPatternForNumber() protected method

protected hasFormattingPatternForNumber ( PhoneNumber $number ) : boolean
$number PhoneNumber
return boolean

hasUnexpectedItalianLeadingZero() protected method

Returns true if a number is from a region whose national significant number couldn't contain a leading zero, but has the italian_leading_zero field set to true.
protected hasUnexpectedItalianLeadingZero ( PhoneNumber $number ) : boolean
$number PhoneNumber
return boolean

hasValidCountryCallingCode() protected method

Helper function to check the country calling code is valid.
protected hasValidCountryCallingCode ( integer $countryCallingCode ) : boolean
$countryCallingCode integer
return boolean

init() protected method

protected init ( )

initAlphaPhoneMappings() protected static method

protected static initAlphaPhoneMappings ( )

initCapturingExtnDigits() protected static method

protected static initCapturingExtnDigits ( )

initDiallableCharMappings() protected static method

protected static initDiallableCharMappings ( )

initExtnPattern() protected static method

protected static initExtnPattern ( )

initExtnPatterns() protected static method

protected static initExtnPatterns ( )

initMobileTokenMappings() protected static method

protected static initMobileTokenMappings ( )

initValidStartCharPattern() protected static method

protected static initValidStartCharPattern ( )

isAlphaNumber() public method

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 {@link #isPossibleNumberWithReason} and {@link #isValidNumber} should be used.
public isAlphaNumber ( string $number ) : boolean
$number string the number that needs to be checked
return boolean true if the number is a valid vanity number

isLeadingZeroPossible() public method

Checks whether the country calling code is from a region whose national significant number could contain a leading zero. An example of such a region is Italy. Returns false if no metadata for the country is found.
public isLeadingZeroPossible ( integer $countryCallingCode ) : boolean
$countryCallingCode integer
return boolean

isMobileNumberPortableRegion() public method

Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability.
public isMobileNumberPortableRegion ( string $regionCode ) : boolean
$regionCode string the region for which we want to know whether it supports mobile number portability or not.
return boolean

isNANPACountry() public method

Checks if this is a region under the North American Numbering Plan Administration (NANPA).
public isNANPACountry ( string $regionCode ) : boolean
$regionCode string
return boolean true if regionCode is one of the regions under NANPA

isNationalNumberSuffixOfTheOther() protected method

Returns true when one national number is the suffix of the other or both are the same.
protected isNationalNumberSuffixOfTheOther ( PhoneNumber $firstNumber, PhoneNumber $secondNumber ) : boolean
$firstNumber PhoneNumber
$secondNumber PhoneNumber
return boolean

isNumberGeographical() public method

Tests whether a phone number has a geographical association. It checks if the number is associated to a certain region in the country where it belongs to. 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.
public isNumberGeographical ( PhoneNumber | integer $phoneNumberObjOrType, integer | null $countryCallingCode = null ) : boolean
$phoneNumberObjOrType PhoneNumber | integer A PhoneNumber object, or a PhoneNumberType integer
$countryCallingCode integer | null Used when passing a PhoneNumberType
return boolean

isNumberMatch() public method

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.

public isNumberMatch ( $firstNumberIn, $secondNumberIn ) : integer
$firstNumberIn PhoneNumber|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.
$secondNumberIn PhoneNumber|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.
return integer {MatchType} NOT_A_NUMBER, NO_MATCH,

isNumberMatchingDesc() public method

public isNumberMatchingDesc ( string $nationalNumber, PhoneNumberDesc $numberDesc ) : boolean
$nationalNumber string
$numberDesc PhoneNumberDesc
return boolean

isPossibleNumber() public method

This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)} with the resultant PhoneNumber object.

public isPossibleNumber ( PhoneNumber | string $number, string $regionDialingFrom = null ) : boolean
$number PhoneNumber | string the number that needs to be checked, in the form of a string
$regionDialingFrom string the 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 boolean true if the number is possible

isPossibleNumberWithReason() public method

  • 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.
  • For fixed line numbers, many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial the subscriber number only when dialing in the same area. This function will return true 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.
  • public isPossibleNumberWithReason ( PhoneNumber $number ) : integer
    $number PhoneNumber the number that needs to be checked
    return integer a ValidationResult object which indicates whether the number is possible

    isValidNumber() public method

    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.
    public isValidNumber ( PhoneNumber $number ) : boolean
    $number PhoneNumber the phone number that we want to validate
    return boolean that indicates whether the number is of a valid pattern

    isValidNumberForRegion() public method

    Warning: In most cases, you want to use {@link #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.
    public isValidNumberForRegion ( PhoneNumber $number, string $regionCode ) : boolean
    $number PhoneNumber the phone number that we want to validate
    $regionCode string the region that we want to validate the phone number for
    return boolean that indicates whether the number is of a valid pattern

    isValidRegionCode() protected method

    Helper function to check region code is not unknown or null.
    protected isValidRegionCode ( string $regionCode ) : boolean
    $regionCode string
    return boolean

    isViablePhoneNumber() public static method

    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.
    public static isViablePhoneNumber ( string $number ) : boolean
    $number string to be checked for viability as a phone number
    return boolean true if the number could be a phone number of some sort, otherwise false

    maybeAppendFormattedExtension() protected method

    Appends the formatted extension of a phone number to formattedNumber, if the phone number had an extension specified.
    protected maybeAppendFormattedExtension ( PhoneNumber $number, PhoneMetadata | null $metadata, integer $numberFormat, string &$formattedNumber )
    $number PhoneNumber
    $metadata PhoneMetadata | null
    $numberFormat integer PhoneNumberFormat
    $formattedNumber string

    maybeExtractCountryCode() public method

    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.
    public maybeExtractCountryCode ( string $number, PhoneMetadata $defaultRegionMetadata = null, string &$nationalNumber, boolean $keepRawInput, PhoneNumber $phoneNumber ) : integer
    $number string non-normalized telephone number that we wish to extract a country calling code from - may begin with '+'
    $defaultRegionMetadata PhoneMetadata metadata about the region this number may be from
    $nationalNumber string a 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.
    $keepRawInput boolean true if the country_code_source and preferred_carrier_code fields of phoneNumber should be populated.
    $phoneNumber PhoneNumber the 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 integer the country calling code extracted or 0 if none could be extracted

    maybeStripExtension() protected method

    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.
    protected maybeStripExtension ( string &$number ) : string
    $number string the non-normalized telephone number that we wish to strip the extension from
    return string the phone extension

    maybeStripInternationalPrefixAndNormalize() public method

    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.
    public maybeStripInternationalPrefixAndNormalize ( string &$number, string $possibleIddPrefix ) : integer
    $number string the non-normalized telephone number that we wish to strip any international dialing prefix from.
    $possibleIddPrefix string string the international direct dialing prefix from the region we think this number may be dialed in
    return integer the 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() public method

    Strips any national prefix (such as 0, 1) present in the number provided.
    public maybeStripNationalPrefixAndCarrierCode ( string &$number, PhoneMetadata $metadata, string &$carrierCode ) : boolean
    $number string the normalized telephone number that we wish to strip any national dialing prefix from
    $metadata PhoneMetadata the metadata for the region that we think this number is from
    $carrierCode string a place to insert the carrier code if one is extracted
    return boolean true if a national prefix or carrier code (or both) could be extracted.

    normalize() public static method

    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.
    public static normalize ( string &$number ) : string
    $number string a string of characters representing a phone number.
    return string the normalized string version of the phone number.

    normalizeDiallableCharsOnly() public static method

    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).
    public static normalizeDiallableCharsOnly ( string $number ) : string
    $number string a string of characters representing a phone number
    return string the normalized string version of the phone number

    normalizeDigits() public static method

    public static normalizeDigits ( string $number, boolean $keepNonDigits ) : string
    $number string
    $keepNonDigits boolean
    return string

    normalizeDigitsOnly() public static method

    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.
    public static normalizeDigitsOnly ( $number ) : string
    $number string a string of characters representing a phone number
    return string the normalized string version of the phone number

    normalizeHelper() protected static method

    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 static normalizeHelper ( string $number, array $normalizationReplacements, boolean $removeNonMatches ) : string
    $number string a string of characters representing a phone number
    $normalizationReplacements array a mapping of characters to what they should be replaced by in the normalized version of the phone number
    $removeNonMatches boolean indicates 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 string the normalized string version of the phone number

    parse() public method

    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 {@link 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 {@link #isValidnumber}.

    public parse ( string $numberToParse, string $defaultRegion, PhoneNumber $phoneNumber = null, boolean $keepRawInput = false ) : PhoneNumber
    $numberToParse string number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension.
    $defaultRegion string region 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.
    $phoneNumber PhoneNumber
    $keepRawInput boolean
    return PhoneNumber a phone number proto buffer filled with the parsed number

    parseAndKeepRawInput() public method

    Parses a string and returns it in proto buffer format. This method differs from {@link #parse} in that it always populates the raw_input field of the protocol buffer with numberToParse as well as the country_code_source field.
    public parseAndKeepRawInput ( string $numberToParse, string $defaultRegion, PhoneNumber $phoneNumber = null ) : PhoneNumber
    $numberToParse string number 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.
    $defaultRegion string region 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.
    $phoneNumber PhoneNumber
    return PhoneNumber a phone number proto buffer filled with the parsed number

    parseHelper() protected method

    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").
    protected parseHelper ( string $numberToParse, string $defaultRegion, boolean $keepRawInput, boolean $checkRegion, PhoneNumber $phoneNumber )
    $numberToParse string
    $defaultRegion string
    $keepRawInput boolean
    $checkRegion boolean
    $phoneNumber PhoneNumber

    parsePrefixAsIdd() protected method

    Strips the IDD from the start of the number if present. Helper function used by maybeStripInternationalPrefixAndNormalize.
    protected parsePrefixAsIdd ( string $iddPattern, string &$number ) : boolean
    $iddPattern string
    $number string
    return boolean

    prefixNumberWithCountryCallingCode() protected method

    A helper function that is used by format and formatByPattern.
    protected prefixNumberWithCountryCallingCode ( integer $countryCallingCode, integer $numberFormat, string &$formattedNumber )
    $countryCallingCode integer
    $numberFormat integer PhoneNumberFormat
    $formattedNumber string

    rawInputContainsNationalPrefix() protected method

    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.
    protected rawInputContainsNationalPrefix ( string $rawInput, string $nationalPrefix, string $regionCode ) : boolean
    $rawInput string
    $nationalPrefix string
    $regionCode string
    return boolean

    resetInstance() public static method

    Used for testing purposes only to reset the PhoneNumberUtil singleton to null.
    public static resetInstance ( )

    setItalianLeadingZerosForPhoneNumber() public static method

    A helper function to set the values related to leading zeros in a PhoneNumber.
    public static setItalianLeadingZerosForPhoneNumber ( string $nationalNumber, PhoneNumber $phoneNumber )
    $nationalNumber string
    $phoneNumber PhoneNumber

    stringEndsWithString() protected method

    protected stringEndsWithString ( $hayStack, $needle )

    testNumberLength() protected method

    Helper method to check a number against possible lengths for this number, and determine whether it matches, or is too short or too long. Currently, if a number pattern suggests that numbers of length 7 and 10 are possible, and a number in between these possible lengths is entered, such as of length 8, this will return TOO_LONG.
    protected testNumberLength ( string $number, PhoneNumberDesc $phoneNumberDesc ) : integer
    $number string
    $phoneNumberDesc PhoneNumberDesc
    return integer ValidationResult

    truncateTooLongNumber() public method

    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.
    public truncateTooLongNumber ( PhoneNumber $number ) : boolean
    $number PhoneNumber a PhoneNumber object which contains a number that is too long to be valid.
    return boolean true if a valid phone number can be successfully extracted.

    Property Details

    $ALL_PLUS_NUMBER_GROUPING_SYMBOLS protected_oe static_oe property

    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 " ".
    protected static array $ALL_PLUS_NUMBER_GROUPING_SYMBOLS
    return array

    $ALPHA_MAPPINGS protected_oe static_oe property

    Only upper-case variants of alpha characters are stored.
    protected static array $ALPHA_MAPPINGS
    return array

    $ALPHA_PHONE_MAPPINGS protected_oe static_oe property

    For performance reasons, amalgamate both into one map.
    protected static array $ALPHA_PHONE_MAPPINGS
    return array

    $CAPTURING_DIGIT_PATTERN protected_oe static_oe property

    protected static $CAPTURING_DIGIT_PATTERN

    $CAPTURING_EXTN_DIGITS protected_oe static_oe property

    protected static $CAPTURING_EXTN_DIGITS

    $DIALLABLE_CHAR_MAPPINGS protected_oe static_oe property

    protected static $DIALLABLE_CHAR_MAPPINGS

    $EXTN_PATTERN protected_oe static_oe property

    protected static $EXTN_PATTERN

    $EXTN_PATTERNS_FOR_PARSING protected_oe static_oe property

    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.
    protected static String $EXTN_PATTERNS_FOR_PARSING
    return String

    $GEO_MOBILE_COUNTRIES protected_oe static_oe property

    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).
    protected static array $GEO_MOBILE_COUNTRIES
    return array

    $GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES protected_oe static_oe property

    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.
    protected static array $GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES
    return array

    $MIN_LENGTH_PHONE_NUMBER_PATTERN protected_oe static_oe property

    protected static $MIN_LENGTH_PHONE_NUMBER_PATTERN

    $MOBILE_TOKEN_MAPPINGS protected_oe static_oe property

    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.
    protected static array $MOBILE_TOKEN_MAPPINGS
    return array

    $PLUS_CHARS_PATTERN public_oe static_oe property

    public static $PLUS_CHARS_PATTERN

    $SECOND_NUMBER_START_PATTERN protected_oe static_oe property

    protected static $SECOND_NUMBER_START_PATTERN

    $SEPARATOR_PATTERN protected_oe static_oe property

    protected static $SEPARATOR_PATTERN

    $UNWANTED_END_CHAR_PATTERN protected_oe static_oe property

    protected static $UNWANTED_END_CHAR_PATTERN

    $VALID_PHONE_NUMBER protected_oe static_oe property

    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.
    protected static string $VALID_PHONE_NUMBER
    return string

    $VALID_PHONE_NUMBER_PATTERN protected_oe static_oe property

    protected static $VALID_PHONE_NUMBER_PATTERN

    $VALID_START_CHAR_PATTERN protected_oe static_oe property

    protected static $VALID_START_CHAR_PATTERN

    $asciiDigitMappings protected_oe static_oe property

    Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
    protected static array $asciiDigitMappings
    return array

    $countryCallingCodeToRegionCodeMap protected_oe property

    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.
    protected array $countryCallingCodeToRegionCodeMap
    return array

    $countryCodesForNonGeographicalRegion protected_oe property

    The set of county calling codes that map to the non-geo entity region ("001").
    protected array $countryCodesForNonGeographicalRegion
    return array

    $instance protected_oe static_oe property

    protected static PhoneNumberUtil,libphonenumber $instance
    return PhoneNumberUtil

    $metadataSource protected_oe property

    protected MetadataSourceInterface,libphonenumber $metadataSource
    return libphonenumber\MetadataSourceInterface

    $nanpaRegions protected_oe property

    The set of regions that share country calling code 1.
    protected array $nanpaRegions
    return array

    $numericCharacters protected_oe static_oe property

    protected static $numericCharacters

    $supportedRegions protected_oe property

    The set of regions the library supports.
    protected array $supportedRegions
    return array