bug #2366 Use null rather than specific length for 'to the end' in mb_substr (arjenm)

This PR was merged into the 2.x branch.

Discussion
----------

Use null rather than specific length for 'to the end' in mb_substr

We use Twig with a ISO-8859-15 charset and noticed the 'capitalize'-method only yielded the first character of a string. I.e. "abcd" became "A" rather than "Abcd".

This was due to a change in the way mb_substr is used. Appearantly, using 2147483647 as a length to indicate 'everything to the end' only works with UTF-8 (and possibly other multibyte charsets). It probably triggers some internal overflow in php for at least ASCII and ISO-8859-15.

Luckily, an easy fix is available since PHP 5.4.8: just use 'null'

See these two tests for which version does what:
(old) https://3v4l.org/qdpIK
(new) https://3v4l.org/kivqK

I also used null in the slice-method. While it did not suffer from this same issue, it did an unnecessary mb_strlen. And there might be similar overflow issues with negative values of $start, but I didn't actually test that.

Commits
-------

3bea610e Use null rather than specific length for 'all characters to the end' with mb_substr
This commit is contained in:
Fabien Potencier
2017-01-17 07:18:35 -08:00
+2 -2
View File
@@ -594,7 +594,7 @@ function twig_slice(Twig_Environment $env, $item, $start, $length = null, $prese
$item = (string) $item;
return (string) mb_substr($item, $start, null === $length ? mb_strlen($item, $env->getCharset()) - $start : $length, $env->getCharset());
return (string) mb_substr($item, $start, $length, $env->getCharset());
}
/**
@@ -1168,7 +1168,7 @@ function twig_capitalize_string_filter(Twig_Environment $env, $string)
{
$charset = $env->getCharset();
return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, 2147483647, $charset), $charset);
return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, null, $charset), $charset);
}
/**