Symfony News

New in Symfony 5.1: String improvements

The String component was introduced in Symfony 5.0 as an experimental feature. In Symfony 5.1 we've improved it with new features.

Use Stringable interface

Contributed by
Nicolas Grekas
in #36059.

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

Contributed by
Fran Moreno
in #35649.

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

Contributed by
Nicolas Grekas
in #35936.

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

Contributed by
Thomas Calvet
in #35091.

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 @ by at. In Symfony 5.1 it will also replace & by and (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 a u() (Unicode string) or a b() (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).

Be trained by Symfony experts - 2020-04-6 Online Europe - 2020-04-6 Online Europe - 2020-04-8 Online Europe


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook