-2

Sorry, I didnt realize I was suppose to say that I have already looked over the other thread dealing with phone numbers. I have tried a few of those and could not get it to work how I needed it. So thats why I decided to ask it myself with the specifics I needed.

I need a function that can format phone number into (555) 555-5555 format.

Examples of the phone numbers im formatting are:

5555555555

555-555-5555

Some numbers that are in the array are already in the correct format.

Dawson
  • 23
  • 4
  • I have a function that i use that can help you – Yeak Jul 26 '22 at 17:12
  • @Yeak thanks but I got it working now due to Markus's answer. – Dawson Jul 26 '22 at 17:25
  • $phone = preg_replace("/[^0-9]/", "", $phone); $length = strlen($phone); switch($length) { case 7: return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone); break; case 10: return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1)$2-$3", $phone); break; case 11: return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2)$3-$4", $phone); break; default: return $phone; break; } – Yeak Jul 26 '22 at 17:27

1 Answers1

0

I would replace all non-numeric characters first, and then reformat. Using regular expressions makes this easy.

$number = '555-555-5555';
$numberOnly = preg_replace('/[^0-9]/', '', $number);
$formattedNumber = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', '($1) $2-$3', $numberOnly);

echo $formattedNumber;

gives the formatted output:

(555) 555-5555
Markus Zeller
  • 8,516
  • 2
  • 29
  • 35
  • 1
    Thanks. Replacing seemed to do the trick. Before I didnt replace and formatted straight away, and while it worked, it ended up with undesired results for some other information in my code, but this seemed to work great. – Dawson Jul 26 '22 at 17:23