The String component provides an object-oriented API to strings and deals with bytes, UTF-8 code points, and grapheme clusters in a unified way. In Symfony 7.2 we've improved it with new features.
Added a kebab()
Method
The String component already defines some methods to change the case of given
strings. For example, camel()
to use camelCase (Foo bar
-> fooBar
)
and snake()
to use snake_case (Foo Bar
-> foo_bar
). In Symfony 7.2
we're introducing kebab()
to use kebab-case:
1 2 3 4 5
use function Symfony\Component\String\u;
$string = u('symfonyIsGreat')->kebab(); // $string = 'symfony-is-great'
$string = u('Symfony is great')->kebab(); // $string = 'symfony-is-great'
$string = u('Symfony_is_Great')->kebab(); // $string = 'symfony-is-great'
New Truncation Modes
The String component defines a truncate()
method with two working modes:
1 2 3 4
// by default, contents are cut to strictly meet the desired length
u('Lorem Ipsum')->truncate(8); // 'Lorem Ip'
// but you can also keep the last word entirely, even if that generates a longer string
u('Lorem Ipsum')->truncate(8, cut: false); // 'Lorem Ipsum'
In Symfony 7.2, we're adding new modes via the TruncateMode::*
constants:
1 2 3 4 5 6 7 8 9 10
// the default value is TruncateMode::Char which cuts the string at the exact given length
// (this is the same as the previous default behavior)
u('Lorem ipsum dolor')->truncate(8, cut: TruncateMode::Char); // 'Lorem ip'
// returns up to the last complete word that fits in the given length without surpassing it
u('Lorem ipsum dolor')->truncate(8, cut: TruncateMode::WordBefore); // 'Lorem'
// returns up to the last complete word that fits in the given length, surpassing it if needed
// (this is the same as setting `cut: false` in the previous example)
u('Lorem ipsum dolor')->truncate(8, cut: TruncateMode::WordAfter); // 'Lorem ipsum'
New Spanish Inflector
Most human languages have numerous exceptions and edge-case rules for converting singular to plural and vice versa. Inflectors help you solve this problem by returning the correct singular or plural form of a given word for the target language.
The String component already includes an inflector for English and French. In Symfony 7.2 we're adding a new inflector for the Spanish language:
1 2 3 4 5 6 7 8
use Symfony\Component\String\Inflector\SpanishInflector;
$inflector = new SpanishInflector();
// all inflectors return arrays instead of strings because sometimes it's not
// possible to determine a unique singular/plural form for the given word
$inflector->singularize('aviones'); // returns ['avión']
$inflector->pluralize('miércoles'); // returns ['miércoles']