From 8cde52d2225adcc53e72b538660e377b3a06fc68 Mon Sep 17 00:00:00 2001 From: 1emming Date: Fri, 3 Oct 2014 11:25:38 +0200 Subject: [PATCH] Fix MB characters handling in split --- lib/Twig/Extension/Core.php | 22 ++++++++++++++++++- test/Twig/Tests/Fixtures/filters/split.test | 2 + test/Twig/Tests/Fixtures/filters/split_utf8.test | 24 ++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 test/Twig/Tests/Fixtures/filters/split_utf8.test diff --git a/lib/Twig/Extension/Core.php b/lib/Twig/Extension/Core.php index 761d737..539bb0c 100644 --- a/lib/Twig/Extension/Core.php +++ b/lib/Twig/Extension/Core.php @@ -173,7 +173,7 @@ class Twig_Extension_Core extends Twig_Extension // array helpers new Twig_SimpleFilter('join', 'twig_join_filter'), - new Twig_SimpleFilter('split', 'twig_split_filter'), + new Twig_SimpleFilter('split', 'twig_split_filter', array('needs_environment' => true)), new Twig_SimpleFilter('sort', 'twig_sort_filter'), new Twig_SimpleFilter('merge', 'twig_array_merge'), new Twig_SimpleFilter('batch', 'twig_array_batch'), @@ -796,9 +796,27 @@ function twig_join_filter($value, $glue = '') * * @return array The split string as an array */ -function twig_split_filter($value, $delimiter, $limit = null) +function twig_split_filter(Twig_Environment $env, $value, $delimiter, $limit = null) { if (empty($delimiter)) { + if (function_exists('mb_get_info') && null !== $charset = $env->getCharset()) { + if ($limit > 1) { + $length = mb_strlen($value, $charset); + if ($length < $limit) { + return array($value); + } + + $r = array(); + for ($i = 0; $i < $length; $i += $limit) { + $r[] = mb_substr($value, $i, $limit, $charset); + } + + return $r; + } + + return preg_split('/(? 'Ä,é,Äほ', 'baz' => 'éÄßごa',) +--EXPECT-- +é +Ä-é-Äほ +Ä,é,Äほ +Ä-é,Äほ +Ä-é-Äほ +é-Ä-ß-ご-a +é-Ä-ß-ご-a +éÄ-ßご-a \ No newline at end of file -- 1.7.2.5