user1032531
user1032531

Reputation: 26311

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?

Upvotes: 11

Views: 13441

Answers (5)

Taylor Evanson
Taylor Evanson

Reputation: 412

Here's how to do it in Symfony.

namespace AppBundle\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension {
    public function getFilters() {
        return [
            new TwigFilter('phone', [$this, 'phoneFilter']),
        ];
    }

    public function phoneFilter($phoneNumber) {
        if (substr($phoneNumber, 0, 2) == "+1") {
            return preg_replace("/(\+1)(\d{3})(\d{3})(\d{4})/", "$1 ($2) $3-$4", $phoneNumber);
        }
        return preg_replace("/(\d{3})(\d{3})(\d{4})/", "($1) $2-$3", $phoneNumber);
    }
}

Upvotes: 4

Araújo Everson
Araújo Everson

Reputation: 75

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

Upvotes: 0

Snopzer
Snopzer

Reputation: 1702

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

Upvotes: -2

user1032531
user1032531

Reputation: 26311

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 }}

Upvotes: 13

Anwar
Anwar

Reputation: 4246

$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 !

Upvotes: 1

Related Questions