skip to Main Content

In the database i have a field in the customers table called customers_telephone.
i want the output the telephone number like this(555) 555-5555.
within this CMS (oscommerce) the output on invoice.php looks like this.

<td class="main"><?php echo $order->customer['telephone']; ?></td>

i found a code that may work:

<?php
function format_telephone($phone_number)
{
    $cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
    preg_match('/(d{3})(d{3})(d{4})/', $cleaned, $matches);
    return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
}
?>
<?php echo format_telephone($customer_phone); ?>

but i am confused where to place this and what variables to insert, i only need the format, only here and for US phones only.

3

Answers


  1. That’s ok.

    In Invoice.php file make sure you have this following block of code before you use it in the <td

    <?php
    function format_telephone($phone_number)
    {
        $cleaned = preg_replace('/[^[:digit:]]/', '', $phone_number);
        preg_match('/(d{3})(d{3})(d{4})/', $cleaned, $matches);
        return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
    }
    ?>
    

    So put his line of code above somewhere, then in this line of code make sure you have

    <td class="main"><?php echo format_telephone($order->customer['telephone']); ?></td>
    

    That’s it. You need to have the function before you use it on the code. Let us know if you have additional issues.

    Login or Signup to reply.
  2. You can use regular expression

    $phone_numbers = array( 
        '555-555-5555',
        '5555425555',
        '555 555 5555',
        '1(519) 555-4444',
        '1 (519) 555-4422',
        '1-555-555-5555',
        '1-(555)-555-25555',
    );
    $regex = "/^(d[s-]?)?[([s-]{0,2}?d{3}[)]s-]{0,2}?d{3}[s-]?d{4}$/i";
    foreach( $phone_numbers as $number ) {
        echo $number . ': ' . ( preg_match( $regex, $number ) ? 'valid' : 'invalid' ) . '<br/>';
    }
    
    
    555-555-5555: valid
    5555425555: valid
    555 555 5555: valid
    1(519) 555-4444: valid
    1 (519) 555-4422: valid
    1-555-555-5555: valid
    1-(555)-555-5555: valid
    1-(555)-555-25555: invalid
    
    Login or Signup to reply.
  3. If you have code for a function, for example:

    <?php
    function hello($hi) {
    return($hi);
    }
    echo(hello("hey"));
    ?>
    

    This would echo ‘hey’.

    Anyway, now to the point: you would want to run the following to echo the phone number.

    <td class="main"><?php echo format_telephone($order->customer['telephone']); ?></td>
    

    Make sure that you add the function code before you try and call it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search