How do you format a 10 digit string into a phone number?

dmanexe picture dmanexe · Jan 19, 2010 · Viewed 57.3k times · Source

I have database records in the form of 10 character long strings, such as 4085551234.

I wish to format these into this format: (408) 555-1234.

I think this is regex related. I'm new to programming and completely self-taught here, so any sort of resource relating to performing text processing would be appreciated as well. Thanks!

Answer

SoapBox picture SoapBox · Jan 19, 2010

A regex is definitely overkill for this one. If you wanted to take a "phone number" and normalize it to 10 digits, that would be a good use for a regex. To do what you're asking, just do something like:

echo '('.substr($data, 0, 3).') '.substr($data, 3, 3).'-'.substr($data,6);

Since you already know how to divide up your data, you can just use substr or something similar to grab the parts you want. RegEx is useful for matching strings which don't always have a strict format. (Like variable numbers of spaces, variable stuff before or after it, extra dashes, etc). But in your case the input is always strictly formatted 10 digits, nothing else, so you don't need the extra overhead of a RegEx to format it.