Last active
February 22, 2022 04:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage in a Twig template: