Fix split trailing newline

This commit is contained in:
Fabien Potencier
2026-09-25 07:33:47 +02:00
parent c8d782ea0b
commit 00861d50ab
3 changed files with 20 additions and 4 deletions
+2
View File
@@ -1,5 +1,7 @@
# 3.30.0 (2026-XX-XX)
* Fix `split`, `random`, and `shuffle` merging a trailing newline into the last character of a string
* Speed up splitting a string into characters in `split`, `random`, and `shuffle`
* Speed up adding extensions to an environment
* Fix the escaping safe analysis retaining every compiled template node for the lifetime of the environment
* Speed up loading a template that the environment has already loaded
+4 -4
View File
@@ -1263,19 +1263,19 @@ final class CoreExtension extends AbstractExtension
}
/**
* Unicode version of str_split(): splits at every position except after the start and before the end.
* Unicode version of str_split(), an empty string giving a single empty character.
*
* @return list<string>
* @return non-empty-list<string>
*
* @throws RuntimeError When the string cannot be split into characters
*/
private static function splitIntoCharacters(string $string, string $name): array
{
if (false === $characters = preg_split('/(?<!^)(?!$)/u', $string)) {
if (false === preg_match_all('/./us', $string, $matches)) {
throw new RuntimeError(\sprintf('Unable to split the string passed to "%s" into characters: %s.', $name, preg_last_error_msg()));
}
return $characters;
return $matches[0] ?: [''];
}
/**
@@ -0,0 +1,14 @@
--TEST--
"reverse", "split", "shuffle", and "random" keep a trailing newline as its own character
--TEMPLATE--
{{ value|reverse|json_encode|raw }}
{{ value|split('')|json_encode|raw }}
{{ value|shuffle|length }}
{{ random("a\n")|length }}
--DATA--
return ['value' => "ab\n"]
--EXPECT--
"\nba"
["a","b","\n"]
3
1