2

I want to display phone number in this format XXX-XXX-XXXX. But now it's displaying like this XXX-XXX-XXX-X

<div class="row mb15">
    <div class="col-12 col-md-5">
        <p>Home Phone</p>
    </div>
    <div class="col-12 col-md-7 phone-number">
        <h4><?php echo join('-', str_split($candidateDet['homephone'], 3)); ?></h4>
    </div>
</div>

Alternative ideas are welcome

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Siva Ganesh
  • 1,415
  • 2
  • 16
  • 28
  • The result is absolutely coherent with your code. Since your formatting is irregular, you may make an iterative function that explicitly take the first 3 char, insert '-', 3 next, insert '-' and append the rest. – nicolallias Mar 06 '18 at 08:08
  • Possible duplicate of [Formatting Phone Numbers in PHP](https://stackoverflow.com/questions/4708248/formatting-phone-numbers-in-php) – Edmund Dzakson Mar 06 '18 at 08:08
  • Remember the conventional way of displaying phone numbers varies by country. So, f you are targeting an international audience you might want to localise this appropriately. – Ian Cook Mar 06 '18 at 08:35
  • thank you all. For your valuable reply – Siva Ganesh Mar 06 '18 at 08:40

1 Answers1

4

You could use preg_replace() to find and group the numbers.

Something like:

echo preg_replace('#(\d{3})(\d{3})(\d{4})#', '$1-$2-$3', $phoneNumber);

An example.

jeroen
  • 91,079
  • 21
  • 114
  • 132