Last active
May 2, 2024 12:08
Format UK Phone Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
$original = '+44 (0)1234 567 890'; | |
$original = '0044 01234 567 890'; | |
$original = '01234 567 890'; | |
$original = '44 1234 567 890'; | |
Result should always be: | |
'+441234567890 | |
*/ | |
// Strip out all characters apart from numbers | |
$phone = preg_replace('/[^0-9]+/', '', $original); | |
// Remove the 2 digit international code (+44) | |
if (substr($phone, 0, 2) == '44') { | |
$phone = substr($phone, 2); | |
} | |
// Remove the 4 digit international code (0044) | |
if (substr($phone, 0, 4) == '0044') { | |
$phone = substr($phone, 4); | |
} | |
// Remove the initial Zero from the number | |
// Some people write it in international numbers like this: +44 (0)1234 567 890 | |
// But it shouldn't be entered when dialling | |
if (substr($phone, 0, 1) == '0') { | |
$phone = substr($phone, 1); | |
} | |
// Add the international prefix | |
$phone = '+44' . $phone; |
Is it ok?
$phone_no = preg_replace( '/[^0-9]/', '', $phone_no );
$phone_no = '+44' . substr($phone_no, -10, 10);
This won't work, as some UK numbers are only 4 or 5 digits long, + area code.
Hope this might help, i've tweaked it a little:
function format_uk_phone($original) {
/*
$original = '+44 (0)1234 567 890';
$original = '0044 01234 567 890';
$original = '01234 567 890';
$original = '44 1234 567 890';
Result should always be:
'+441234567890
*/
// Strip out all characters apart from numbers
$phone = preg_replace( '/[^0-9]+/', '', $original );
if ( substr( $phone, 0, 2 ) == '00' ) {
// Remove the international code (00)
$phone = substr( $phone, 2 );
}
if ( substr( $phone, 0, 2 ) == '44' ) {
// Remove the international code (44)
$phone = substr( $phone, 2 );
}
if ( substr( $phone, 0, 1 ) == '0' ) {
// Remove the initial Zero from the number
$phone = substr( $phone, 1 );
}
if ( in_array(substr( $phone, 0, 1 ), array('1','2','7') ) && (strlen($phone) <= 10) ) {
// Some people write it in international numbers like this: +44 (0)1234 567 890
// But it shouldn't be entered when dialling
// This is probably a UK number
} else {
// Phone is not a UK number
$phone = '';
}
if ( $phone !== '' ) {
// Add the international prefix
$phone = '+44' . $phone;
}
return $phone;
}
Thanks @lukearmstrong
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @lukearmstrong