使用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?

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 }}
$numberPhone = '4155551212';
$firstChain = substr($numberPhone, 0, 3);
$secondChain = substr($numberPhone, 3, 3);
$thirdChain = substr($numberPhone, 6, 4);
$formatedNumberPhone = '(' . $firstChain . ') ' . $secondChain . '-' . $thirdChain;

echo $formatedNumberPhone;

Here is the solution for those who have similar question about it.

Little bit explaination about how substr() works :

It take three arguments in this case :

  1. The chain you want to modify
  2. The index which represent the place where the function will begin his process
  3. How many caracters you want to preserve

Note that you can pass negative value to the second and third argument (go to official doc for further information).

In this case, I am taking the first caracter of the phone number, so I'll tell the function to begin from 0 and to keep 3 caracters, so it looks like I did : susbtr($numberPhone, 0, 3).

Hope it helps !

Phone Number in US Format : {{phone_number | phone | default("-")}}

Eu fiz assim: {{ p.number[:4] }} - {{ p.number[4:]}}
I did that way: {{ p.number[:4] }} - {{ p.number[4:]}}