Reputation: 625
I am looking to format a phone number with twig. Basically, I wanted to separate every 2 digits with this function and it works perfectly when I have a 10-digit phone number like 0600000000:
{% set splitPhone = store.phones['phone_store']|split('', 2) %}
{% set phone = splitPhone|join(' ') %}
I get what I want:
06 00 00 00 00
The problem is that my data can also arrive in the form: +336000000
so in that case I get
+3 36 00 00 00
I would like something like : + 336 00 00 00
In this case, I would like to find a general technique to ensure that if my number is 10 digits, it does as I currently do but in case there is the "+" in front, it separates it from the digits.
Do you know how I can do this?
Upvotes: 0
Views: 227
Reputation: 15621
You can just extend twig with a custom filter which solves this for you, e.g.
$twig->addFilter(new \Twig\TwigFilter('format_phone', function($phone) {
$prefix = null;
if (strpos($phone, '+') === 0) $prefix = substr($phone, 0, 4).' ';
$temp = str_split(substr($phone, $prefix ? 4 : 0), 2);
return $prefix.implode(' ', $temp);
});
{{ '0600000000'|format_phone }}
{{ '+336000000'|format_phone }}
Upvotes: 1