phpjquerylaravel

I want to Display Phone number in this format XXX-XXX-XXXX. I tried many way but cant get the correct answer


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


Solution

  • 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.