user1032531 user1032531 - 1 month ago 39
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

4155551212
.

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

How is this best accomplished?

Answer

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

<?php
require_once '../../../vendor/autoload.php';
Twig_Autoloader::register();
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());
}
?>

filter.html

{{ phone|phone }}