Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a telephone number using Twig

Tags:

php

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?

like image 971
user1032531 Avatar asked Sep 25 '14 17:09

user1032531


3 Answers

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 }}
like image 82
user1032531 Avatar answered Oct 04 '22 03:10

user1032531


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

like image 28
Anwar Avatar answered Oct 04 '22 03:10

Anwar


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);
    }
}
like image 27
Taylor Evanson Avatar answered Oct 04 '22 04:10

Taylor Evanson