6

Can an integer be formatted as a telephone number using Twig filters or other methods?

I have looked at the 'number_format' filter but it seems to be limited to controlling the number of decimals and how to delimited thousands.

Example; Integer variable from cms '20304050', output to HTML in twig like this: '20 30 40 50'.

1 Answer 1

8

Assuming that you always want to add a space after every two digits, something like this using Twig's split and join filters should work:

{% set splitArray = "20304050"|split('', 2) %}
{% set formattedString = splitArray|join(' ') %}

If you want a different format, like 203 04 050, then you could use slice:

{% set firstSeg = "20404050"|slice(0, 3) %}
{% set secondSeg = "20404050"|slice(3, 2) %}
{% set thirdSeg = "20404050"|slice(5, 3) %}

{% set formattedString = firstSeg ~ ' ' ~ secondSeg ~ ' ' ~ thirdSeg %}
2
  • What if we need to split it like this: 203 04 050
    – Alf Vestre
    Commented Oct 1, 2014 at 20:45
  • Updated answer.
    – Brad Bell
    Commented Oct 1, 2014 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.