I am working on an SMS app and need to be able to convert the sender\'s phone number from +11234567890 to 123-456-7890 so it can be compared to re
I know the OP is requesting a 123-456-7890 format, but, based on John Dul's answer, I modified it to return the phone number in parentheses format, e.g. (123) 456-7890. This one only handles 7 and 10 digit numbers.
function format_phone_string( $raw_number ) {
// remove everything but numbers
$raw_number = preg_replace( '/\D/', '', $raw_number );
// split each number into an array
$arr_number = str_split($raw_number);
// add a dummy value to the beginning of the array
array_unshift( $arr_number, 'dummy' );
// remove the dummy value so now the array keys start at 1
unset($arr_number[0]);
// get the number of numbers in the number
$num_number = count($arr_number);
// loop through each number backward starting at the end
for ( $x = $num_number; $x >= 0; $x-- ) {
if ( $x === $num_number - 4 ) {
// before the fourth to last number
$phone_number = "-" . $phone_number;
}
else if ( $x === $num_number - 7 && $num_number > 7 ) {
// before the seventh to last number
// and only if the number is more than 7 digits
$phone_number = ") " . $phone_number;
}
else if ( $x === $num_number - 10 ) {
// before the tenth to last number
$phone_number = "(" . $phone_number;
}
// concatenate each number (possibly with modifications) back on
$phone_number = $arr_number[$x] . $phone_number;
}
return $phone_number;
}