--- /dev/null
+``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"] #}
// 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'),
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.
--- /dev/null
+--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