A common task in working with client projects is to normalize phone numbers. Customers on the sites can enter the phone number in international format, in local format, with or without brackets, with or without a plus in the beginning.
Our Studio has developed its universal method for Ukrainian phone numbers which enables to bring phone number into local or international format: either 0991234567 or +380991234567
If you write in Laravel or similar systems, you can add this method to helpers.php as auxiliary.
function normalize_phone_number($s, $internation = true)
{
$s = trim($s);
$s = preg_replace('/[^0-9]/', '', $s);
$s = preg_replace('/^[+]?380/', '0', $s);
if (strlen($s) === 11 && substr($s, 0, 1) === '8') $s = substr($s, 1);
if (strlen($s) === 11 && substr($s, 0, 2) === '38') $s = '0' . substr($s, 2);
if (strlen($s) === 12 && substr($s, 0, 2) === '38') $s = substr($s, 2);
if (!$internation) {
return $s;
}
return $s = '+38' . $s;
}
Let's test now:
echo normalize_phone_number('380(99)123-45-678');
+3809912345678
echo normalize_phone_number('380(99)123-45-678', false);
09912345678
Now at least for Ukrainian phones you can not suffer 😄