Skip to content

Instantly share code, notes, and snippets.

@aklump
Last active April 24, 2024 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aklump/a45dd706e4153cfbe150e83cb6226e69 to your computer and use it in GitHub Desktop.
Save aklump/a45dd706e4153cfbe150e83cb6226e69 to your computer and use it in GitHub Desktop.
class FormatPhoneNumber {
const FORMAT = '(%d) %d-%d';
const SMS_FORMAT = '+1%d%d%d';
public function __invoke(string $number, string $format = NULL) {
$number = preg_replace('#[^0-9]#', '', $number);
preg_match('#(.+)?(\d{3})(\d{3})(\d{4})$#', $number, $matches);
array_shift($matches);
array_shift($matches);
$matches = array_filter($matches);
$format = $format ?? self::FORMAT;
array_unshift($matches, $format);
return call_user_func_array('sprintf', $matches);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment