user1032531 user1032531 - 1 year ago 483
PHP Question

Format a telephone number using Twig

I have phone numbers stored in a database using char(10), and they look for example as


I wish a Twig template to display them as
(415) 555-1212

How is this best accomplished?

Answer Source

It would be nice not to have to add this filter every time, but it will meet my needs.

require_once '../../../vendor/autoload.php';
try {
    $loader = new Twig_Loader_Filesystem('templates');
    $twig = new Twig_Environment($loader, array('debug' => true,));
    $twig->addExtension(new Twig_Extension_Debug());
    $twig->addFilter(new Twig_SimpleFilter('phone', function ($num) {
        return ($num)?'('.substr($num,0,3).') '.substr($num,3,3).'-'.substr($num,6,4):'&nbsp;';
    echo $twig->render('filter.html', array('phone'=>'4155551212'));
} catch (Exception $e) {
    die ('ERROR: ' . $e->getMessage());


{{ phone|phone }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download