Skip to content

Instantly share code, notes, and snippets.

@grandsilence
Created March 13, 2019 11:07
Show Gist options
  • Save grandsilence/685f47ca702d4815ed688823e33e64e3 to your computer and use it in GitHub Desktop.
Save grandsilence/685f47ca702d4815ed688823e33e64e3 to your computer and use it in GitHub Desktop.
Convert international phone +79004001234 to +7 900 400 12-34. Or local Russian 88004001234 to 8 800 400 12 34. Raw
<?php
function pretty_phone($phone) {
if (!preg_match('/^(\+?)(\d)(\d{3})(\d{3})(\d{2})(\d{2})$/', $phone, $matches)) {
return 'invalid phone';
}
$is_international = !empty($matches[0]) && $matches[0] === '+';
$last_delimiter = $is_international ? '-' : ' ';
$delimeters = [' ', ' ', $last_delimiter, $last_delimiter];
$result = $matches[1] . $matches[2]; // +7 or 8
for ($i = 3; $i <= 6; $i++) {
$result .= $delimeters[$i - 3] . $matches[$i];
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment