Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Filters split
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x, 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

split

The split filter splits a string by the given delimiter and returns a list of strings:

1
2
{% set items = "one,two,three"|split(',') %}
{# items contains ['one', 'two', 'three'] #}

You can also pass a limit argument:

  • If limit is positive, the returned sequence will contain a maximum of limit elements with the last element containing the rest of string;
  • If limit is negative, all components except the last -limit are returned;
  • If limit is zero, then this is treated as 1.
1
2
{% set items = "one,two,three,four,five"|split(',', 3) %}
{# items contains ['one', 'two', 'three,four,five'] #}

If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default).

1
2
3
4
5
{% set items = "123"|split('') %}
{# items contains ['1', '2', '3'] #}

{% set items = "aabbcc"|split('', 2) %}
{# items contains ['aa', 'bb', 'cc'] #}

Note

Internally, Twig uses the PHP explode or str_split (if delimiter is empty) functions for string splitting.

Arguments

  • delimiter: The delimiter
  • limit: The limit argument