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?
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):' ';
}));
echo $twig->render('filter.html', array('phone'=>'4155551212'));
} catch (Exception $e) {
die ('ERROR: ' . $e->getMessage());
}
?>
filter.html
{{ phone|phone }}
$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 :
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 !
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With