The String component was introduced in Symfony 5.0 as an experimental feature. In Symfony 5.1 it will be no longer experimental and we've improved it with new features.
Use Stringable
interface
PHP 8 will be published in December 2020, but you can already use some of its
features in your PHP applications thanks to the Symfony PHP 8 Polyfill. In
Symfony 5.1 we use that polyfill to make all string objects implement the
Stringable
interface.
This will allow you to use union types such as string|Stringable
in the
future when you later upgrade to PHP 8.
Keep the last word when truncating
When truncating text with the truncate()
method, it's common to keep the
last word unchanged, even if that means generating a string slightly longer than
initially desired.
That is now possible thanks to a new optional argument called cut
which is
true
by default. Set it to false
to keep the last word unchanged:
1 2 3 4
use function Symfony\Component\String\u;
u('Lorem Ipsum')->truncate(8, '…'); // 'Lorem I…'
u('Lorem Ipsum')->truncate(8, '…', false); // 'Lorem Ipsum'
Added a containsAny()
method
A common need when working with strings is to check if a given string contains
some other string. That's why we added a new containsAny()
method, which not
only checks if a string contains another one, but it can also check if it
contains at least one of all the given strings:
1 2 3 4 5
use function Symfony\Component\String\u;
u('aeiou')->containsAny('a'); // true
u('aeiou')->containsAny(['ab', 'efg']); // false
u('aeiou')->containsAny(['eio', 'foo', 'z']); // true
Added a reverse()
method
Another method added in Symfony 5.1 is reverse()
, which flips the order
of the string contents:
1 2 3 4
use function Symfony\Component\String\u;
u('foo bar')->reverse(); // 'rab oof'
u('さよなら')->reverse(); // 'らなよさ'
Other improvements
- The slugger changes some special characters to generate better slugs. For example,
it replaces
@
byat
. In Symfony 5.1 it will also replace&
byand
(this was contributed by Warxcell in #35689); - We added a new
s()
helper to quickly create string objects without having to think if you need au()
(Unicode string) or ab()
(Binary string) (this was contributed by Thomas Calvet in #35625); - The
width()
method, which returns the width needed to display a character in the console, now follows the POSIX.1-2001 standard (this was contributed by Thomas Calvet in #35156).
Isn't it a bit strange to always translate '&' to the English 'and'? If you're making a slug of a dutch sentence with an '&' in it, it would result in a slug with an English word in it, or does it take local into account?
@Kevin I've created an issue to ask about this: https://github.com/symfony/symfony/issues/36383