Format your phone number with Twig

I have phone numbers stored in the database using char (10) and they look like 4155551212 , for example.

I want the Twig template to display them as (415) 555-1212 .

How is this best done?

+5
source share
4 answers

It would be nice not 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 }} 
+9
source
 $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 a solution for those who have a similar question.

It explains a little how substr () works:

In this case, three arguments:

  • The chain you want to change
  • The index that represents the place where the function starts its process
  • How many characters do you want to keep

Please note that you can pass a negative value to the second and third argument (refer to the white paper for more information).

In this case, I take the first character of the phone number, so I will say that the function starts with 0 and hold 3 characters, so it looks like this: susbtr($numberPhone, 0, 3) .

Hope this helps!

+1
source

US phone number: {{phone_number | phone | default ( "-" )}}

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

Source: https://habr.com/ru/post/1203418/


All Articles