views:

295

answers:

5

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!

A: 

Replace (...)(...)(....) with (\1) \2-\3.

Ignacio Vazquez-Abrams
Doesn't really help at all.
Nick Bedford
+1 to counter people who don't understand what you're saying. `preg_replace("/(...)(...)(....)/","(...)(...)(....)",$string);`
slebetman
So Stack Overflow is about assuming people know or realise everything?
Nick Bedford
+5  A: 

Take a look here: Format phone number

function format_phone($phone)
{
    $phone = preg_replace("/[^0-9]/", "", $phone);

    if(strlen($phone) == 7)
        return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
    elseif(strlen($phone) == 10)
        return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
    else
        return $phone;
}
Rubens Farias
+10  A: 

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.

SoapBox
I like the methodology behind this one the most. Thanks a lot! I can see how you did what you did, and I learned a bit about substr(). Thanks!
dmanexe
+1  A: 

Trivially you could do something like:

\(\d\{3\}\)\(\d\{3\}\)\(\d\{4\}\)

To match the 10 digits into 3 subgroup expressions, and then print them out using each subgroup:

"(\1) \2-\3

But in practice free form data is usually a little trickier

John Weldon
+1  A: 

I'd probably go with

$num = "4085551234";  // given                                                  
$formatted = "(".substr($num,0,3).") ".substr($num,3,3)."-".substr($num,6);

Regex isn't really appropriate here.

Grumdrig
Thanks! Similar to the above mentioned solution I went with.
dmanexe