Skip to content

Commit

Permalink
Added "split" filter aka explode.
Browse files Browse the repository at this point in the history
  • Loading branch information
gnikyt authored and Konstantin G Romanov committed Aug 18, 2012
1 parent 657de7b commit e3c201a
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions doc/filters/index.rst
Expand Up @@ -18,6 +18,7 @@ Filters
lower
striptags
join
split
reverse
length
sort
Expand Down
16 changes: 16 additions & 0 deletions doc/filters/split.rst
@@ -0,0 +1,16 @@
``split``
========

The ``split`` filter returns a list of items from a string that's separated by the provided delimiter or glue:

.. code-block:: jinja
{{ "one,two,three"|split(',') }}
{# returns [one, two, three] #}
A limit parameter is available which the returned list will contain a maximum of limit elements with the last element containing the rest of string.

.. code-block:: jinja
{{ "one,two,three,four,five"|split(',', 3) }}
{# returns [one, two, "three,four,five"] #}
33 changes: 33 additions & 0 deletions lib/Twig/Extension/Core.php
Expand Up @@ -145,6 +145,7 @@ public function getFilters()

// array helpers
'join' => new Twig_Filter_Function('twig_join_filter'),
'split' => new Twig_Filter_Function('twig_split_filter'),
'sort' => new Twig_Filter_Function('twig_sort_filter'),
'merge' => new Twig_Filter_Function('twig_array_merge'),

Expand Down Expand Up @@ -650,6 +651,38 @@ function twig_join_filter($value, $glue = '')
return implode($glue, (array) $value);
}

/**
* Splits the values into an array.
*
* The second parameter is option for the limit.
*
* <pre>
* {{ "one,two,three"|split(',') }}
* {# returns [one, two, three] #}
*
* {{ "one,two,three,four,five"|split(',', 3) }}
* {# returns [one, two, "three,four,five"] #}
* </pre>
*
* @param string $value A string
* @param string $delimiter The separator to explode by
* @param integer $limit The limit
*
* @return string The explode'ed string
*/
function twig_split_filter($value, $delimiter, $limit = null)
{
if (is_empty($delimiter)) {
throw new Twig_Error_Runtime('The string to split must be provided with a delimiter.');
}

if (!is_null($limit)) {
return explode($delimiter, $value, $limit);
}

return explode($delimiter, $value);
}

// The '_default' filter is used internally to avoid using the ternary operator
// which costs a lot for big contexts (before PHP 5.4). So, on average,
// a function call is cheaper.
Expand Down
12 changes: 12 additions & 0 deletions test/Twig/Tests/Fixtures/filters/split.test
@@ -0,0 +1,12 @@
--TEST--
"split" filter
--TEMPLATE--
{{ "one,two,three,four,five"|split(',')|join('-') }}
{{ foo|split(',')|join('-') }}
{{ bar|split(',', 3)|join('-') }}
--DATA--
return array('foo' => "one,two,three,four,five", 'bar' => "one,two,three,four,five")
--EXPECT--
one-two-three-four-five
one-two-three-four-five
one-two-three,four,five

0 comments on commit e3c201a

Please sign in to comment.