Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``split`` |
| 2 | ========= |
| 3 | |
| 4 | The ``split`` filter splits a string by the given delimiter and returns a list |
| 5 | of strings: |
| 6 | |
| 7 | .. code-block:: twig |
| 8 | |
| 9 | {% set foo = "one,two,three"|split(',') %} |
| 10 | {# foo contains ['one', 'two', 'three'] #} |
| 11 | |
| 12 | You can also pass a ``limit`` argument: |
| 13 | |
| 14 | * If ``limit`` is positive, the returned array will contain a maximum of |
| 15 | limit elements with the last element containing the rest of string; |
| 16 | |
| 17 | * If ``limit`` is negative, all components except the last -limit are |
| 18 | returned; |
| 19 | |
| 20 | * If ``limit`` is zero, then this is treated as 1. |
| 21 | |
| 22 | .. code-block:: twig |
| 23 | |
| 24 | {% set foo = "one,two,three,four,five"|split(',', 3) %} |
| 25 | {# foo contains ['one', 'two', 'three,four,five'] #} |
| 26 | |
| 27 | If the ``delimiter`` is an empty string, then value will be split by equal |
| 28 | chunks. Length is set by the ``limit`` argument (one character by default). |
| 29 | |
| 30 | .. code-block:: twig |
| 31 | |
| 32 | {% set foo = "123"|split('') %} |
| 33 | {# foo contains ['1', '2', '3'] #} |
| 34 | |
| 35 | {% set bar = "aabbcc"|split('', 2) %} |
| 36 | {# bar contains ['aa', 'bb', 'cc'] #} |
| 37 | |
| 38 | .. note:: |
| 39 | |
| 40 | Internally, Twig uses the PHP `explode`_ or `str_split`_ (if delimiter is |
| 41 | empty) functions for string splitting. |
| 42 | |
| 43 | Arguments |
| 44 | --------- |
| 45 | |
| 46 | * ``delimiter``: The delimiter |
| 47 | * ``limit``: The limit argument |
| 48 | |
| 49 | .. _`explode`: https://secure.php.net/explode |
| 50 | .. _`str_split`: https://secure.php.net/str_split |