File: split.rst

package info (click to toggle)
php-twig 2.14.3-1%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,240 kB
  • sloc: php: 18,830; makefile: 215; sh: 42; python: 33
file content (50 lines) | stat: -rw-r--r-- 1,345 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
``split``
=========

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

.. code-block:: twig

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

You can also pass a ``limit`` argument:

* If ``limit`` is positive, the returned array 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.

.. code-block:: twig

    {% set foo = "one,two,three,four,five"|split(',', 3) %}
    {# foo 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).

.. code-block:: twig

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

    {% set bar = "aabbcc"|split('', 2) %}
    {# bar 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

.. _`explode`:   https://secure.php.net/explode
.. _`str_split`: https://secure.php.net/str_split