libphonenumber\PhoneNumberUtil::getNddPrefixForRegion PHP Method

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
    public function getNddPrefixForRegion($regionCode, $stripNonDigits)
    {
        $metadata = $this->getMetadataForRegion($regionCode);
        if ($metadata === null) {
            return null;
        }
        $nationalPrefix = $metadata->getNationalPrefix();
        // If no national prefix was found, we return null.
        if (mb_strlen($nationalPrefix) == 0) {
            return null;
        }
        if ($stripNonDigits) {
            // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
            // to be removed here as well.
            $nationalPrefix = str_replace("~", "", $nationalPrefix);
        }
        return $nationalPrefix;
    }

Usage Example

 public function testGetNationalDiallingPrefixForRegion()
 {
     $this->assertEquals("1", $this->phoneUtil->getNddPrefixForRegion(RegionCode::US, false));
     // Test non-main country to see it gets the national dialling prefix for the main country with
     // that country calling code.
     $this->assertEquals("1", $this->phoneUtil->getNddPrefixForRegion(RegionCode::BS, false));
     $this->assertEquals("0", $this->phoneUtil->getNddPrefixForRegion(RegionCode::NZ, false));
     // Test case with non digit in the national prefix.
     $this->assertEquals("0~0", $this->phoneUtil->getNddPrefixForRegion(RegionCode::AO, false));
     $this->assertEquals("00", $this->phoneUtil->getNddPrefixForRegion(RegionCode::AO, true));
     // Test cases with invalid regions.
     $this->assertNull($this->phoneUtil->getNddPrefixForRegion(null, false));
     $this->assertNull($this->phoneUtil->getNddPrefixForRegion(RegionCode::ZZ, false));
     $this->assertNull($this->phoneUtil->getNddPrefixForRegion(RegionCode::UN001, false));
     // CS is already deprecated so the library doesn't support it.
     $this->assertNull($this->phoneUtil->getNddPrefixForRegion(RegionCode::CS, false));
 }
PhoneNumberUtil