Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 617
dmanexe Avatar asked Jan 18 '10 23:01

dmanexe


People also ask

How do you format a 10-digit phone number?

If you do not want the parentheses-space-hyphen formatting (800) 555-1212 for a 10- or 11-digit number, enter a “+” before the number.

How do you format a phone number?

To format phone numbers in the US, Canada, and other NANP (North American Numbering Plan) countries, enclose the area code in parentheses followed by a nonbreaking space, and then hyphenate the three-digit exchange code with the four-digit number.

How do you enter a phone number in a valid format?

You should provide the complete number, including the country code with no use of special characters or spaces. Just the number. For example, a phone number like +1-555-555-1212 should be formatted as 15555551212 .

Is there a phone number format in Excel?

Excel provides a special number format that lets you format a number as a phone number. For example, you can format a 10-digit number, such as 5555551234, as (555) 555-1234. Select the cell or range of cells that you want to format.


1 Answers

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.

like image 75
SoapBox Avatar answered Oct 11 '22 18:10

SoapBox