How to display dashes in phone number?

3 posts by 2 authors in: Forums > CMS Builder
Last Post: October 30, 2015   (RSS)

By geminiman7 - October 28, 2015

Hi everyone,

In CMSB, I have been collecting phone numbers for member records as just 10 digits together with no dashes. So in in the database itself, it's showing as "##########".

What I want to do on the visual front end is show visual dashes automatically, so it displays as "###-###-####".

How can this be achieved?

By Dave - October 29, 2015

Hi geminiman7,

For many simple PHP questions you can just Google for "PHP" followed by the questions asked a few different ways.

I found some results with this query:  https://www.google.ca/search?q=php+add+dashes+to+phone+number

I don't know an especially simple or elegant way to do it, but this works: 

$number = "1234567890";
$withDashes = preg_replace("/\d\d\d/", '$0-', $number, 2);

print "$number<br/>\n";     // outputs: 1234567890
print "$withDashes<br/>\n"; // outputs: 123-456-7890
exit;

The preg_replace line basically means: Match 3 digits blocks ("\d\d\d"), and replace those with whatever you matched ($0) followed by a dash, and only do it 2 times.

Hope that helps!

Dave Edis - Senior Developer
interactivetools.com

By geminiman7 - October 30, 2015

Thanks, Dave.  I did Google that right after posting and found a few different solutions, too. I couldn't get two of them to work (I don't understand PHP programming/logic very well), but did find another solution that was a complete script, and it worked. Here's what it was:

<?php
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;

}
?>

I saw comments in some other sites about this not being the best solution, but I don't understand why. As long as it's working for me it's fine, I guess!