Skip to content

Instantly share code, notes, and snippets.

@davidmintz
Last active February 22, 2022 04:05
Show Gist options
  • Save davidmintz/8b532e1a1387bdf2c8b8769c997fdd9b to your computer and use it in GitHub Desktop.
Save davidmintz/8b532e1a1387bdf2c8b8769c997fdd9b to your computer and use it in GitHub Desktop.
Symfony/Twig filter for rendering US 10-digit phone numbers +1xxxxxxxxx as (xxx) xxx-xxxx
<?php
namespace App\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class AppExtension extends AbstractExtension
{
public function getFilters() : Array
{
return [ new TwigFilter('phone',[$this, 'format']) ];
}
public function format(string $phone) : String
{
return preg_replace('/^\+?1?(\d{3})(\d{3})(\d{4})$/', '($1) $2-$3', $phone);
}
}
```
@davidmintz
Copy link
Author

davidmintz commented Feb 22, 2022

Usage in a Twig template:

{{ person.phone | phone }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment