tags:

views:

94

answers:

5

So I have a string that stores the phone numbers like so, $phone = "123456790". How can I split it to print it in this format: 123-456-7890 ?

+7  A: 
$areacode = substr($phone, 0, 3);
$prefix   = substr($phone, 3, 3);
$number   = substr($phone, 6, 4);

echo "$areacode-$prefix-$number";

You could also do it with regular expressions:

preg_match("/(\d{3})(\d{3})(\d{4})/",$phone,$matches);
echo "$matches[1]-$matches[2]-$matches[3]";

There are more ways, but either will work.

Erik
+1 for the nice reg-ex
Arms
+1  A: 
echo substr($phone, 0, 3) . '-' . substr($phone, 3, 3) . '-' . substr($phone, 6);

substr()

Amber
+3  A: 

The following code will also validate your input.

preg_match('/^(\d{3})(\d{3})(\d{4})$/', $phone, $matches);

if ($matches) {
    echo(implode('-', array_slice($matches, 1)));
}
else {
    echo($phone); // you might want to handle wrong format another way
}
codeholic
+1  A: 
$p = $phone; 
echo "$p[0]$p[1]$p[2]-$p[3]$p[4]-$p[5]$p[6]$p[7]$p[8]";

Fewest function calls. :)

mrclay
A: 

More regexp :)

$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);
Ch4m3l3on