/** * Strips any national prefix (such as 0, 1) present in the number provided. * * @param string $number the normalized telephone number that we wish to strip any national * dialing prefix from * @param PhoneMetadata $metadata the metadata for the region that we think this number is from * @param string $carrierCode a place to insert the carrier code if one is extracted * @return bool true if a national prefix or carrier code (or both) could be extracted. */ public function maybeStripNationalPrefixAndCarrierCode(&$number, PhoneMetadata $metadata, &$carrierCode) { $numberLength = mb_strlen($number); $possibleNationalPrefix = $metadata->getNationalPrefixForParsing(); if ($numberLength == 0 || $possibleNationalPrefix === null || mb_strlen($possibleNationalPrefix) == 0) { // Early return for numbers of zero length. return false; } // Attempt to parse the first digits as a national prefix. $prefixMatcher = new Matcher($possibleNationalPrefix, $number); if ($prefixMatcher->lookingAt()) { $nationalNumberRule = $metadata->getGeneralDesc()->getNationalNumberPattern(); // Check if the original number is viable. $nationalNumberRuleMatcher = new Matcher($nationalNumberRule, $number); $isViableOriginalNumber = $nationalNumberRuleMatcher->matches(); // $prefixMatcher->group($numOfGroups) === null implies nothing was captured by the capturing // groups in $possibleNationalPrefix; therefore, no transformation is necessary, and we just // remove the national prefix $numOfGroups = $prefixMatcher->groupCount(); $transformRule = $metadata->getNationalPrefixTransformRule(); if ($transformRule === null || mb_strlen($transformRule) == 0 || $prefixMatcher->group($numOfGroups - 1) === null) { // If the original number was viable, and the resultant number is not, we return. $matcher = new Matcher($nationalNumberRule, substr($number, $prefixMatcher->end())); if ($isViableOriginalNumber && !$matcher->matches()) { return false; } if ($carrierCode !== null && $numOfGroups > 0 && $prefixMatcher->group($numOfGroups) !== null) { $carrierCode .= $prefixMatcher->group(1); } $number = substr($number, $prefixMatcher->end()); return true; } else { // Check that the resultant number is still viable. If not, return. Check this by copying // the string and making the transformation on the copy first. $transformedNumber = $number; $transformedNumber = substr_replace($transformedNumber, $prefixMatcher->replaceFirst($transformRule), 0, $numberLength); $matcher = new Matcher($nationalNumberRule, $transformedNumber); if ($isViableOriginalNumber && !$matcher->matches()) { return false; } if ($carrierCode !== null && $numOfGroups > 1) { $carrierCode .= $prefixMatcher->group(1); } $number = substr_replace($number, $transformedNumber, 0, mb_strlen($number)); return true; } } return false; }