Files

32 lines
927 B
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
/** North American Numbering Plan normalization to E.164 (+1NXXNXXXXXX). */
final class Phone
{
public static function normalizeNanp(string $input): ?string
{
$digits = preg_replace('/\D+/', '', $input) ?? '';
if (strlen($digits) === 11 && $digits[0] === '1') {
$digits = substr($digits, 1);
}
if (strlen($digits) !== 10) {
return null;
}
$area = substr($digits, 0, 3);
$exchange = substr($digits, 3, 3);
if (in_array($area[0], ['0', '1'], true) || in_array($exchange[0], ['0', '1'], true)) {
return null;
}
if ($area[1] === '1' && $area[2] === '1') {
return null; // N11 service codes
}
return '+1' . $digits;
}
public static function isE164(string $v): bool
{
return (bool)preg_match('/^\+[1-9]\d{6,14}$/', $v);
}
}