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