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 ?
views:
94answers:
5
+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
2010-02-23 00:36:29
+1 for the nice reg-ex
Arms
2010-02-23 02:33:43
+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
2010-02-23 00:43:49
+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
2010-02-23 03:31:24
A:
More regexp :)
$phone = "1234567890";
echo preg_replace('/^(\d{3})(\d{3})(\d{4})$/', '\1-\2-\3', $phone);
Ch4m3l3on
2010-02-23 11:22:06